Example usage for java.util.concurrent.atomic AtomicBoolean set

List of usage examples for java.util.concurrent.atomic AtomicBoolean set

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicBoolean set.

Prototype

public final void set(boolean newValue) 

Source Link

Document

Sets the value to newValue , with memory effects as specified by VarHandle#setVolatile .

Usage

From source file:ch.cyberduck.core.SingleTransferWorkerTest.java

@Test
public void testTransferredSizeRepeat() throws Exception {
    final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    final byte[] content = new byte[62768];
    new Random().nextBytes(content);
    final OutputStream out = local.getOutputStream(false);
    IOUtils.write(content, out);/*from   w ww  . j a v  a  2 s . co  m*/
    out.close();
    final Host host = new Host(new DAVProtocol(), "test.cyberduck.ch",
            new Credentials(System.getProperties().getProperty("webdav.user"),
                    System.getProperties().getProperty("webdav.password")));
    host.setDefaultPath("/dav/basic");
    final AtomicBoolean failed = new AtomicBoolean();
    final DAVSession session = new DAVSession(host) {
        final DAVUploadFeature upload = new DAVUploadFeature(this) {
            @Override
            protected InputStream decorate(final InputStream in, final MessageDigest digest)
                    throws IOException {
                if (failed.get()) {
                    // Second attempt successful
                    return in;
                }
                return new CountingInputStream(in) {
                    @Override
                    protected void beforeRead(final int n) throws IOException {
                        super.beforeRead(n);
                        if (this.getByteCount() >= 32768L) {
                            failed.set(true);
                            throw new SocketTimeoutException();
                        }
                    }
                };
            }
        };

        @Override
        @SuppressWarnings("unchecked")
        public <T> T getFeature(final Class<T> type) {
            if (type == Upload.class) {
                return (T) upload;
            }
            return super.getFeature(type);
        }
    };
    session.open(new DisabledHostKeyCallback(), new DisabledTranscriptListener());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path test = new Path(new DefaultHomeFinderService(session).find(), UUID.randomUUID().toString(),
            EnumSet.of(Path.Type.file));
    final Transfer t = new UploadTransfer(new Host(new TestProtocol()), test, local);
    final BytecountStreamListener counter = new BytecountStreamListener(new DisabledStreamListener());
    assertTrue(new SingleTransferWorker(session, t, new TransferOptions(), new TransferSpeedometer(t),
            new DisabledTransferPrompt() {
                @Override
                public TransferAction prompt(final TransferItem file) {
                    return TransferAction.overwrite;
                }
            }, new DisabledTransferErrorCallback(), new DisabledTransferItemCallback(),
            new DisabledProgressListener(), counter, new DisabledLoginCallback(), TransferItemCache.empty()) {

    }.run(session));
    local.delete();
    assertEquals(62768L, counter.getSent(), 0L);
    assertEquals(62768L, new DAVAttributesFeature(session).find(test).getSize());
    assertTrue(failed.get());
    new DAVDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
}

From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java

@Test
public void shouldTimeoutSleepingScript() throws Exception {
    final AtomicBoolean successCalled = new AtomicBoolean(false);
    final AtomicBoolean failureCalled = new AtomicBoolean(false);

    final CountDownLatch timeOutCount = new CountDownLatch(1);

    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().scriptEvaluationTimeout(250)
            .afterFailure((b, e) -> failureCalled.set(true)).afterSuccess((b) -> successCalled.set(true))
            .afterTimeout((b) -> timeOutCount.countDown()).create();
    try {// ww w  .ja  v a 2 s  .co  m
        gremlinExecutor.eval("Thread.sleep(1000);10").get();
        fail("This script should have timed out with an exception");
    } catch (Exception ex) {
        assertEquals(TimeoutException.class, ex.getCause().getClass());
    }

    assertTrue(timeOutCount.await(2000, TimeUnit.MILLISECONDS));

    assertFalse(successCalled.get());
    assertFalse(failureCalled.get());
    assertEquals(0, timeOutCount.getCount());
    gremlinExecutor.close();
}

From source file:net.dempsy.container.TestContainer.java

@Test
public void testEvictCollisionWithBlocking() throws Throwable {
    final TestProcessor mp = createAndGet("foo");

    // now we're going to cause the passivate to be held up.
    mp.blockPassivate = new CountDownLatch(1);
    mp.evict.set(true); // allow eviction

    // now kick off the evict in a separate thread since we expect it to hang
    // until the mp becomes unstuck.
    final AtomicBoolean evictIsComplete = new AtomicBoolean(false); // this will allow us to see the evict pass complete
    final Thread thread = new Thread(new Runnable() {
        @Override//  ww  w  . j  av  a 2  s.c om
        public void run() {
            container.evict();
            evictIsComplete.set(true);
        }
    });
    thread.start();

    Thread.sleep(500); // let it get going.
    assertFalse(evictIsComplete.get()); // check to see we're hung.

    final ClusterMetricGetters sc = (ClusterMetricGetters) statsCollector;
    assertEquals(0, sc.getMessageCollisionCount());

    // sending it a message will now cause it to have the collision tick up
    final TestAdaptor adaptor = context.getBean(TestAdaptor.class);
    adaptor.dispatcher.dispatchAnnotated(new ContainerTestMessage("foo"));

    // give it some time.
    Thread.sleep(100);

    // make sure there's no collision
    assertEquals(0, sc.getMessageCollisionCount());

    // make sure no message got handled
    assertEquals(1, mp.invocationCount); // 1 is the initial invocation that caused the instantiation.

    // now let the evict finish
    mp.blockPassivate.countDown();

    // wait until the eviction completes
    assertTrue(poll(evictIsComplete, o -> o.get()));

    // Once the poll finishes a new Mp is instantiated and handling messages.
    assertTrue(poll(cache, c -> c.get("foo") != null));
    final TestProcessor mp2 = cache.get("foo");
    assertNotNull("MP not associated with expected key", mp);

    // invocationCount should be 1 from the initial invocation that caused the clone, and no more
    assertEquals(1, mp.invocationCount);
    assertEquals(1, mp2.invocationCount);
    assertTrue(mp != mp2);

    // send a message that should go through
    adaptor.dispatcher.dispatchAnnotated(new ContainerTestMessage("foo"));
    assertTrue(poll(o -> mp2.invocationCount > 1));
    Thread.sleep(100);
    assertEquals(1, mp.invocationCount);
    assertEquals(2, mp2.invocationCount);
}

From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java

@Test
public void shouldEvalInMultipleThreads() throws Exception {
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().create();

    final CyclicBarrier barrier = new CyclicBarrier(2);
    final AtomicInteger i1 = new AtomicInteger(0);
    final AtomicBoolean b1 = new AtomicBoolean(false);
    final Thread t1 = new Thread(() -> {
        try {// ww  w.  ja  va  2  s . c  o  m
            barrier.await();
            i1.set((Integer) gremlinExecutor.eval("1+1").get());
        } catch (Exception ex) {
            b1.set(true);
        }
    });

    final AtomicInteger i2 = new AtomicInteger(0);
    final AtomicBoolean b2 = new AtomicBoolean(false);
    final Thread t2 = new Thread(() -> {
        try {
            barrier.await();
            i2.set((Integer) gremlinExecutor.eval("1+1").get());
        } catch (Exception ex) {
            b2.set(true);
        }
    });

    t1.start();
    t2.start();

    t1.join();
    t2.join();

    assertEquals(2, i1.get());
    assertEquals(2, i2.get());
    assertFalse(b1.get());
    assertFalse(b2.get());

    gremlinExecutor.close();
}

From source file:io.atomix.protocols.gossip.map.AntiEntropyMapDelegate.java

@Override
public V put(K key, V value) {
    checkState(!closed, destroyedMessage);
    checkNotNull(key, ERROR_NULL_KEY);//www . ja v  a 2s . c o  m
    checkNotNull(value, ERROR_NULL_VALUE);

    String encodedKey = encodeKey(key);
    byte[] encodedValue = encodeValue(value);

    MapValue newValue = new MapValue(encodedValue, timestampProvider.get(Maps.immutableEntry(key, value)));

    counter.incrementCount();
    AtomicReference<byte[]> oldValue = new AtomicReference<>();
    AtomicBoolean updated = new AtomicBoolean(false);
    items.compute(encodedKey, (k, existing) -> {
        if (existing == null || newValue.isNewerThan(existing)) {
            updated.set(true);
            oldValue.set(existing != null ? existing.get() : null);
            return newValue;
        }
        return existing;
    });

    if (updated.get()) {
        notifyPeers(new UpdateEntry(encodedKey, newValue),
                peerUpdateFunction.select(Maps.immutableEntry(key, value), membershipService));
        if (oldValue.get() == null) {
            notifyListeners(new MapDelegateEvent<>(INSERT, key, value));
        } else {
            notifyListeners(new MapDelegateEvent<>(UPDATE, key, value));
        }
        return decodeValue(oldValue.get());
    }
    return value;
}

From source file:com.datatorrent.stram.engine.GenericNodeTest.java

private void testCheckpointDistance(int dagCheckPoint, int opCheckPoint) throws InterruptedException {
    int windowWidth = 50;
    long sleeptime = 25L;
    int maxWindows = 60;
    // Adding some extra time for the windows to finish
    long maxSleep = windowWidth * maxWindows + 5000;

    ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1, "default");
    final WindowGenerator windowGenerator = new WindowGenerator(executorService, 1024);
    windowGenerator.setWindowWidth(windowWidth);
    windowGenerator.setFirstWindow(executorService.getCurrentTimeMillis());
    windowGenerator.setCheckpointCount(dagCheckPoint, 0);
    //GenericOperator go = new GenericOperator();
    CheckpointDistanceOperator go = new CheckpointDistanceOperator();
    go.maxWindows = maxWindows;//from w ww. j a va2  s. co  m

    List<Integer> checkpoints = new ArrayList<Integer>();

    int window = 0;
    while (window < maxWindows) {
        window = (int) Math.ceil((double) (window + 1) / dagCheckPoint) * dagCheckPoint;
        window = (int) Math.ceil((double) window / opCheckPoint) * opCheckPoint;
        checkpoints.add(window);
    }

    final StreamContext stcontext = new StreamContext("s1");
    DefaultAttributeMap attrMap = new DefaultAttributeMap();
    attrMap.put(Context.DAGContext.CHECKPOINT_WINDOW_COUNT, dagCheckPoint);
    attrMap.put(Context.OperatorContext.CHECKPOINT_WINDOW_COUNT, opCheckPoint);
    final OperatorContext context = new com.datatorrent.stram.engine.OperatorContext(0, attrMap, null);
    final GenericNode gn = new GenericNode(go, context);
    gn.setId(1);

    //DefaultReservoir reservoir1 = new DefaultReservoir("ip1Res", 1024);
    //DefaultReservoir reservoir2 = new DefaultReservoir("ip2Res", 1024);

    //gn.connectInputPort("ip1", reservoir1);
    //gn.connectInputPort("ip2", reservoir2);
    gn.connectInputPort("ip1", windowGenerator.acquireReservoir("ip1", 1024));
    gn.connectInputPort("ip2", windowGenerator.acquireReservoir("ip2", 1024));
    gn.connectOutputPort("op", Sink.BLACKHOLE);

    final AtomicBoolean ab = new AtomicBoolean(false);
    Thread t = new Thread() {
        @Override
        public void run() {
            gn.setup(context);
            windowGenerator.activate(stcontext);
            gn.activate();
            ab.set(true);
            gn.run();
            windowGenerator.deactivate();
            gn.deactivate();
            gn.teardown();
        }
    };
    t.start();

    long interval = 0;
    do {
        Thread.sleep(sleeptime);
        interval += sleeptime;
    } while ((go.numWindows < maxWindows) && (interval < maxSleep));

    Assert.assertEquals("Number distances", maxWindows, go.numWindows);
    int chkindex = 0;
    int nextCheckpoint = checkpoints.get(chkindex++);
    for (int i = 0; i < maxWindows; ++i) {
        if ((i + 1) > nextCheckpoint) {
            nextCheckpoint = checkpoints.get(chkindex++);
        }
        Assert.assertEquals("Windows from checkpoint for " + i, nextCheckpoint - i, (int) go.distances.get(i));
    }

    gn.shutdown();
    t.join();
}

From source file:org.apache.hadoop.hbase.master.procedure.TestMasterProcedureSchedulerConcurrency.java

@Test(timeout = 60000)
public void testConcurrentCreateDelete() throws Exception {
    final MasterProcedureScheduler procQueue = queue;
    final TableName table = TableName.valueOf("testtb");
    final AtomicBoolean running = new AtomicBoolean(true);
    final AtomicBoolean failure = new AtomicBoolean(false);
    Thread createThread = new Thread() {
        @Override//from w w w . java  2s .co m
        public void run() {
            try {
                TestTableProcedure proc = new TestTableProcedure(1, table,
                        TableProcedureInterface.TableOperationType.CREATE);
                while (running.get() && !failure.get()) {
                    if (procQueue.tryAcquireTableExclusiveLock(proc, table)) {
                        procQueue.releaseTableExclusiveLock(proc, table);
                    }
                }
            } catch (Throwable e) {
                LOG.error("create failed", e);
                failure.set(true);
            }
        }
    };

    Thread deleteThread = new Thread() {
        @Override
        public void run() {
            try {
                TestTableProcedure proc = new TestTableProcedure(2, table,
                        TableProcedureInterface.TableOperationType.DELETE);
                while (running.get() && !failure.get()) {
                    if (procQueue.tryAcquireTableExclusiveLock(proc, table)) {
                        procQueue.releaseTableExclusiveLock(proc, table);
                    }
                    procQueue.markTableAsDeleted(table, proc);
                }
            } catch (Throwable e) {
                LOG.error("delete failed", e);
                failure.set(true);
            }
        }
    };

    createThread.start();
    deleteThread.start();
    for (int i = 0; i < 100 && running.get() && !failure.get(); ++i) {
        Thread.sleep(100);
    }
    running.set(false);
    createThread.join();
    deleteThread.join();
    assertEquals(false, failure.get());
}

From source file:ch.cyberduck.core.worker.SingleTransferWorkerTest.java

@Test
public void testTransferredSizeRepeat() throws Exception {
    final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    final byte[] content = new byte[62768];
    new Random().nextBytes(content);
    final OutputStream out = local.getOutputStream(false);
    IOUtils.write(content, out);//from w w  w  .j  a v a  2  s  .c  o m
    out.close();
    final Host host = new Host(new DAVProtocol(), "test.cyberduck.ch",
            new Credentials(System.getProperties().getProperty("webdav.user"),
                    System.getProperties().getProperty("webdav.password")));
    host.setDefaultPath("/dav/basic");
    final AtomicBoolean failed = new AtomicBoolean();
    final DAVSession session = new DAVSession(host) {
        final DAVUploadFeature upload = new DAVUploadFeature(new DAVWriteFeature(this)) {
            @Override
            protected InputStream decorate(final InputStream in, final MessageDigest digest)
                    throws IOException {
                if (failed.get()) {
                    // Second attempt successful
                    return in;
                }
                return new CountingInputStream(in) {
                    @Override
                    protected void beforeRead(final int n) throws IOException {
                        super.beforeRead(n);
                        if (this.getByteCount() >= 32768L) {
                            failed.set(true);
                            throw new SocketTimeoutException();
                        }
                    }
                };
            }
        };

        @Override
        @SuppressWarnings("unchecked")
        public <T> T _getFeature(final Class<T> type) {
            if (type == Upload.class) {
                return (T) upload;
            }
            return super._getFeature(type);
        }
    };
    session.open(new DisabledHostKeyCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path test = new Path(new DefaultHomeFinderService(session).find(), UUID.randomUUID().toString(),
            EnumSet.of(Path.Type.file));
    final Transfer t = new UploadTransfer(new Host(new TestProtocol()), test, local);
    final BytecountStreamListener counter = new BytecountStreamListener(new DisabledStreamListener());
    assertTrue(new SingleTransferWorker(session, session, t, new TransferOptions(), new TransferSpeedometer(t),
            new DisabledTransferPrompt() {
                @Override
                public TransferAction prompt(final TransferItem file) {
                    return TransferAction.overwrite;
                }
            }, new DisabledTransferErrorCallback(), new DisabledProgressListener(), counter,
            new DisabledLoginCallback(), new DisabledPasswordCallback(), TransferItemCache.empty()) {

    }.run(session, session));
    local.delete();
    assertEquals(62768L, counter.getSent(), 0L);
    assertEquals(62768L, new DAVAttributesFinderFeature(session).find(test).getSize());
    assertTrue(failed.get());
    new DAVDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
}

From source file:org.apache.tez.Tez_1494.java

@Override
public int run(String[] args) throws Exception {
    TezConfiguration tezConf = new TezConfiguration(getConf());

    String[] otherArgs = new GenericOptionsParser(args).getRemainingArgs();

    Preconditions.checkArgument(otherArgs != null && otherArgs.length == 3,
            "Please provide valid map_2_input map_7_input reducer_output path");

    String map_2_input = otherArgs[0];
    String map_7_input = otherArgs[1];
    String output = otherArgs[2];

    TezClient tezClient = TezClient.create("Tez_1494", tezConf, false);
    tezClient.start();//w  w w.  jav a  2 s.  c om
    DAG dag = createDAG(map_2_input, map_7_input, output, tezConf);

    AtomicBoolean shutdown = new AtomicBoolean(false);
    try {
        DAGClient statusClient = tezClient.submitDAG(dag);

        //Start monitor (note: not shutting down thread)
        Monitor monitor = new Monitor(statusClient, shutdown);

        DAGStatus status = statusClient
                .waitForCompletionWithStatusUpdates(EnumSet.of(StatusGetOpts.GET_COUNTERS));

        return (status.getState() == DAGStatus.State.SUCCEEDED) ? 0 : -1;
    } finally {
        if (tezClient != null) {
            tezClient.stop();
        }
        shutdown.set(true);
    }
}

From source file:io.atomix.protocols.gossip.map.AntiEntropyMapDelegate.java

private void processUpdates(Collection<UpdateEntry> updates) {
    if (closed) {
        return;//from ww  w  . j av  a  2 s .  co m
    }
    updates.forEach(update -> {
        final String key = update.key();
        final MapValue value = update.value() == null ? null : update.value().copy();
        if (value == null || value.isTombstone()) {
            MapValue previousValue = removeInternal(key, Optional.empty(), Optional.ofNullable(value));
            if (previousValue != null && previousValue.isAlive()) {
                notifyListeners(
                        new MapDelegateEvent<>(REMOVE, decodeKey(key), previousValue.get(this::decodeValue)));
            }
        } else {
            counter.incrementCount();
            AtomicReference<byte[]> oldValue = new AtomicReference<>();
            AtomicBoolean updated = new AtomicBoolean(false);
            items.compute(key, (k, existing) -> {
                if (existing == null || value.isNewerThan(existing)) {
                    updated.set(true);
                    oldValue.set(existing != null ? existing.get() : null);
                    return value;
                }
                return existing;
            });

            if (updated.get()) {
                if (oldValue.get() == null) {
                    notifyListeners(new MapDelegateEvent<>(INSERT, decodeKey(key), decodeValue(value.get())));
                } else {
                    notifyListeners(new MapDelegateEvent<>(UPDATE, decodeKey(key), decodeValue(value.get())));
                }
            }
        }
    });
}