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

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

Introduction

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

Prototype

public AtomicBoolean(boolean initialValue) 

Source Link

Document

Creates a new AtomicBoolean with the given initial value.

Usage

From source file:io.pravega.client.stream.impl.ReaderGroupStateManager.java

private Map<Segment, Long> acquireSegment(long timeLag) throws ReinitializationRequiredException {
    AtomicReference<Map<Segment, Long>> result = new AtomicReference<>();
    AtomicBoolean reinitRequired = new AtomicBoolean(false);
    sync.updateState(state -> {//from   ww  w  .j a  v a  2s .  c  o  m
        if (!state.isReaderOnline(readerId)) {
            reinitRequired.set(true);
            return null;
        }
        int toAcquire = calculateNumSegmentsToAcquire(state);
        if (toAcquire == 0) {
            result.set(Collections.emptyMap());
            return null;
        }
        Map<Segment, Long> unassignedSegments = state.getUnassignedSegments();
        Map<Segment, Long> acquired = new HashMap<>(toAcquire);
        List<ReaderGroupStateUpdate> updates = new ArrayList<>(toAcquire);
        Iterator<Entry<Segment, Long>> iter = unassignedSegments.entrySet().iterator();
        for (int i = 0; i < toAcquire; i++) {
            assert iter.hasNext();
            Entry<Segment, Long> segment = iter.next();
            acquired.put(segment.getKey(), segment.getValue());
            updates.add(new AcquireSegment(readerId, segment.getKey()));
        }
        updates.add(new UpdateDistanceToTail(readerId, timeLag));
        result.set(acquired);
        return updates;
    });
    if (reinitRequired.get()) {
        throw new ReinitializationRequiredException();
    }
    acquireTimer.reset(calculateAcquireTime(sync.getState()));
    return result.get();
}

From source file:com.nokia.dempsy.container.TestMpContainer.java

@Test
public void testEvictableWithBusyMp() throws Exception {
    // This forces the instantiation of an Mp
    inputQueue.add(serializer.serialize(new ContainerTestMessage("foo")));
    // Once the poll finishes the Mp is instantiated and handling messages.
    assertNotNull(outputQueue.poll(baseTimeoutMillis, TimeUnit.MILLISECONDS));

    assertEquals("did not create MP", 1, container.getProcessorCount());

    TestProcessor mp = (TestProcessor) container.getMessageProcessor("foo");
    assertNotNull("MP not associated with expected key", mp);
    assertEquals("activation count, 1st message", 1, mp.activationCount);
    assertEquals("invocation count, 1st message", 1, mp.invocationCount);

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

    // sending it a message will now cause it to hang up while processing
    inputQueue.add(serializer.serialize(new ContainerTestMessage("foo")));

    // keep track of the cloneCount for later checking
    int tmpCloneCount = TestProcessor.cloneCount.intValue();

    // invocation count should go to 2
    assertTrue(TestUtils.poll(baseTimeoutMillis, mp, new TestUtils.Condition<TestProcessor>() {
        @Override// ww w  . j av  a 2s.  c  o  m
        public boolean conditionMet(TestProcessor o) {
            return o.invocationCount == 2;
        }
    }));

    assertNull(outputQueue.peek()); // this is a double check that no message got all the way 

    // 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
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            container.evict();
            evictIsComplete.set(true);
        }
    });
    thread.start();

    // now check to make sure eviction doesn't complete.
    Thread.sleep(50); // just a little to give any mistakes a change to work themselves through
    assertFalse(evictIsComplete.get()); // make sure eviction didn't finish

    mp.latch.countDown(); // this lets it go

    // wait until the eviction completes
    assertTrue(TestUtils.poll(baseTimeoutMillis, evictIsComplete, new TestUtils.Condition<AtomicBoolean>() {
        @Override
        public boolean conditionMet(AtomicBoolean o) {
            return o.get();
        }
    }));

    // now it comes through.
    assertNotNull(outputQueue.poll(baseTimeoutMillis, TimeUnit.MILLISECONDS));

    assertEquals("activation count, 2nd message", 1, mp.activationCount);
    assertEquals("invocation count, 2nd message", 2, mp.invocationCount);

    inputQueue.add(serializer.serialize(new ContainerTestMessage("foo")));
    assertNotNull(outputQueue.poll(baseTimeoutMillis, TimeUnit.MILLISECONDS));

    assertEquals("Clone count, 2nd message", tmpCloneCount + 1, TestProcessor.cloneCount.intValue());
}

From source file:com.cloudera.whirr.cm.server.impl.CmServerImpl.java

@Override
@CmServerCommandMethod(name = "client")
public boolean getServiceConfigs(final CmServerCluster cluster, final File directory) throws CmServerException {

    final AtomicBoolean executed = new AtomicBoolean(false);
    try {/*from www. jav a 2s .  c o  m*/

        if (isProvisioned(cluster)) {
            logger.logOperation("GetConfig", new CmServerLogSyncCommand() {
                @Override
                public void execute() throws IOException {
                    for (ApiService apiService : apiResourceRootV3.getClustersResource()
                            .getServicesResource(getName(cluster)).readServices(DataView.SUMMARY)) {
                        CmServerServiceType type = CmServerServiceType.valueOfId(apiService.getType());
                        if (type.equals(CmServerServiceType.HDFS) || type.equals(CmServerServiceType.MAPREDUCE)
                                || type.equals(CmServerServiceType.YARN)
                                || type.equals(CmServerServiceType.HBASE)
                                || versionApi >= 4 && type.equals(CmServerServiceType.HIVE)
                                || versionApi >= 5 && type.equals(CmServerServiceType.SOLR)) {
                            ZipInputStream configInputZip = null;
                            try {
                                InputStreamDataSource configInput = apiResourceRootV3.getClustersResource()
                                        .getServicesResource(getName(cluster))
                                        .getClientConfig(apiService.getName());
                                if (configInput != null) {
                                    configInputZip = new ZipInputStream(configInput.getInputStream());
                                    ZipEntry configInputZipEntry = null;
                                    while ((configInputZipEntry = configInputZip.getNextEntry()) != null) {
                                        String configFile = configInputZipEntry.getName();
                                        if (configFile.contains(File.separator)) {
                                            configFile = configFile.substring(
                                                    configFile.lastIndexOf(File.separator),
                                                    configFile.length());
                                        }
                                        directory.mkdirs();
                                        BufferedWriter configOutput = null;
                                        try {
                                            int read;
                                            configOutput = new BufferedWriter(
                                                    new FileWriter(new File(directory, configFile)));
                                            while (configInputZip.available() > 0) {
                                                if ((read = configInputZip.read()) != -1) {
                                                    configOutput.write(read);
                                                }
                                            }
                                        } finally {
                                            configOutput.close();
                                        }
                                    }
                                }
                            } finally {
                                if (configInputZip != null) {
                                    configInputZip.close();
                                }
                            }
                            executed.set(true);
                        }
                    }
                }
            });
        }

    } catch (Exception e) {
        throw new CmServerException("Failed to get cluster config", e);
    }

    return executed.get();

}

From source file:com.arpnetworking.metrics.impl.ApacheHttpSinkTest.java

@Test
public void testBatchesRequests() throws InterruptedException {
    _wireMockRule.stubFor(WireMock.requestMatching(new RequestValueMatcher(r -> {
        // Annotations
        Assert.assertEquals(0, r.getAnnotationsCount());

        // Dimensions
        Assert.assertEquals(0, r.getDimensionsCount());

        // Samples
        assertSample(r.getTimersList(), "timer", 7d);
        assertSample(r.getCountersList(), "counter", 8d);
        assertSample(r.getGaugesList(), "gauge", 9d);
    })).willReturn(WireMock.aResponse().withStatus(200)));

    final AtomicBoolean assertionResult = new AtomicBoolean(false);
    final Semaphore semaphore = new Semaphore(0);
    final Sink sink = new ApacheHttpSink.Builder()
            .setUri(URI.create("http://localhost:" + _wireMockRule.port() + PATH)).setMaxBatchSize(10)
            .setParallelism(1).setEmptyQueueInterval(Duration.ofMillis(1000))
            .setEventHandler(new AttemptCompletedAssertionHandler(assertionResult, 3, 210, true,
                    new CompletionHandler(semaphore)))
            .build();/*from  www . j  a  v a2s .  c  o m*/

    final TsdEvent event = new TsdEvent(Collections.emptyMap(),
            createQuantityMap("timer", TsdQuantity.newInstance(7d, null)),
            createQuantityMap("counter", TsdQuantity.newInstance(8d, null)),
            createQuantityMap("gauge", TsdQuantity.newInstance(9d, null)));

    for (int x = 0; x < 3; x++) {
        sink.record(event);
    }
    semaphore.acquire();

    // Ensure expected handler was invoked
    Assert.assertTrue(assertionResult.get());

    // Request matcher
    final RequestPatternBuilder requestPattern = WireMock.postRequestedFor(WireMock.urlEqualTo(PATH))
            .withHeader("Content-Type", WireMock.equalTo("application/octet-stream"));

    // Assert that data was sent
    _wireMockRule.verify(1, requestPattern);
    Assert.assertTrue(_wireMockRule.findUnmatchedRequests().getRequests().isEmpty());
}

From source file:com.screenslicer.webapp.ScreenSlicerClient.java

@Path("create")
@POST//from   ww w .  j  a v  a 2  s. c  o m
@Consumes("application/json")
@Produces("application/json")
public static final Response create(String reqString) {
    if (reqString != null) {
        final String reqDecoded = Crypto.decode(reqString, CommonUtil.ip());
        if (reqDecoded != null) {
            final Map<String, Object> args = CommonUtil.gson.fromJson(reqDecoded, CommonUtil.objectType);
            final Request request = CommonUtil.gson.fromJson(reqDecoded, Request.class);
            Field[] fields = request.getClass().getFields();
            for (Field field : fields) {
                args.remove(field.getName());
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String myInstance = null;
                    AtomicBoolean myDone = null;
                    try {
                        CommonFile.writeStringToFile(
                                new File("./data/" + request.runGuid + "-meta" + request.appId),
                                request.jobId + "\n" + request.jobGuid + "\n"
                                        + Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTimeInMillis(),
                                false);
                        CommonFile.writeStringToFile(new File("./data/" + request.runGuid + "-context"),
                                Crypto.encode(reqDecoded), false);
                        Map<String, AtomicBoolean> myDoneMap = new HashMap<String, AtomicBoolean>();
                        synchronized (doneMapLock) {
                            for (int i = 0; i < request.instances.length; i++) {
                                if (!doneMap.containsKey(request.instances[i])) {
                                    doneMap.put(request.instances[i], new AtomicBoolean(true));
                                }
                            }
                            myDoneMap.putAll(doneMap);
                        }
                        long myThread = latestThread.incrementAndGet();
                        while (true) {
                            if (isCancelled(request.runGuid)) {
                                curThread.incrementAndGet();
                                throw new CancellationException();
                            }
                            if (myThread == curThread.get() + 1) {
                                for (Map.Entry<String, AtomicBoolean> done : myDoneMap.entrySet()) {
                                    if (done.getValue().compareAndSet(true, false)) {
                                        if (ScreenSlicer.isBusy(done.getKey())) {
                                            done.getValue().set(true);
                                        } else {
                                            myInstance = done.getKey();
                                            myDone = done.getValue();
                                            break;
                                        }
                                    }
                                }
                                if (myInstance != null) {
                                    break;
                                }
                            }
                            try {
                                Thread.sleep(WAIT);
                            } catch (Exception e) {
                                Log.exception(e);
                            }
                        }
                        curThread.incrementAndGet();
                        int outputNumber = 0;
                        request.instances = new String[] { myInstance };
                        Map<String, List<List<String>>> tables = customApp.tableData(request, args);
                        Map<String, Map<String, Object>> jsons = customApp.jsonData(request, args);
                        Map<String, byte[]> binaries = customApp.binaryData(request, args);
                        request.emailExport.attachments = new LinkedHashMap<String, byte[]>();
                        if (tables != null) {
                            for (Map.Entry<String, List<List<String>>> table : tables.entrySet()) {
                                if (table.getKey().toLowerCase().endsWith(".xls")) {
                                    byte[] result = Spreadsheet.xls(table.getValue());
                                    CommonFile.writeByteArrayToFile(
                                            new File("./data/" + request.runGuid + "-result" + outputNumber),
                                            result, false);
                                    CommonFile.writeStringToFile(
                                            new File("./data/" + request.runGuid + "-result-names"),
                                            escapeName(table.getKey()) + "\n", true);
                                    ++outputNumber;
                                    if (request.emailResults) {
                                        request.emailExport.attachments.put(table.getKey(), result);
                                    }
                                } else if (table.getKey().toLowerCase().endsWith(".csv")) {
                                    String result = Spreadsheet.csv(table.getValue());
                                    CommonFile.writeStringToFile(
                                            new File("./data/" + request.runGuid + "-result" + outputNumber),
                                            result, false);
                                    CommonFile.writeStringToFile(
                                            new File("./data/" + request.runGuid + "-result-names"),
                                            escapeName(table.getKey()) + "\n", true);
                                    ++outputNumber;
                                    if (request.emailResults) {
                                        request.emailExport.attachments.put(table.getKey(),
                                                result.getBytes("utf-8"));
                                    }
                                } else if (table.getKey().toLowerCase().endsWith(".xcsv")) {
                                    String result = Spreadsheet.csv(table.getValue());
                                    CommonUtil.internalHttpCall(CommonUtil.ip(),
                                            "https://" + CommonUtil.ip() + ":8000/_/"
                                                    + Crypto.fastHash(table.getKey() + ":" + request.runGuid),
                                            "PUT", CommonUtil.asMap("Content-Type", "text/csv; charset=utf-8"),
                                            result.getBytes("utf-8"), null);
                                    CommonFile.writeStringToFile(
                                            new File("./data/" + request.runGuid + "-result-names"),
                                            escapeName(table.getKey()) + "\n", true);
                                    ++outputNumber;
                                    if (request.emailResults) {
                                        request.emailExport.attachments.put(table.getKey(),
                                                result.getBytes("utf-8"));
                                    }
                                } else {
                                    String result = CommonUtil.gson.toJson(table.getValue(),
                                            table.getValue().getClass());
                                    CommonFile.writeStringToFile(
                                            new File("./data/" + request.runGuid + "-result" + outputNumber),
                                            result, false);
                                    CommonFile.writeStringToFile(
                                            new File("./data/" + request.runGuid + "-result-names"),
                                            escapeName(table.getKey()) + "\n", true);
                                    ++outputNumber;
                                    if (request.emailResults) {
                                        request.emailExport.attachments.put(table.getKey(),
                                                result.getBytes("utf-8"));
                                    }
                                }
                            }
                        }
                        if (jsons != null) {
                            for (Map.Entry<String, Map<String, Object>> json : jsons.entrySet()) {
                                String result = CommonUtil.gson.toJson(json.getValue(), CommonUtil.objectType);
                                CommonFile.writeStringToFile(
                                        new File("./data/" + request.runGuid + "-result" + outputNumber),
                                        result, false);
                                CommonFile.writeStringToFile(
                                        new File("./data/" + request.runGuid + "-result-names"),
                                        escapeName(json.getKey()) + "\n", true);
                                ++outputNumber;
                                if (request.emailResults) {
                                    request.emailExport.attachments.put(json.getKey(),
                                            result.getBytes("utf-8"));
                                }
                            }
                        }
                        if (binaries != null) {
                            for (Map.Entry<String, byte[]> binary : binaries.entrySet()) {
                                CommonFile.writeByteArrayToFile(
                                        new File("./data/" + request.runGuid + "-result" + outputNumber),
                                        binary.getValue(), false);
                                CommonFile.writeStringToFile(
                                        new File("./data/" + request.runGuid + "-result-names"),
                                        escapeName(binary.getKey()) + "\n", true);
                                ++outputNumber;
                                if (request.emailResults) {
                                    request.emailExport.attachments.put(binary.getKey(), binary.getValue());
                                }
                            }
                        }
                        if (request.emailResults) {
                            ScreenSlicer.export(request, request.emailExport);
                        }
                    } catch (Throwable t) {
                        Log.exception(t);
                    } finally {
                        try {
                            CommonFile.writeStringToFile(
                                    new File("./data/" + request.runGuid + "-meta" + request.appId),
                                    "\n" + Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTimeInMillis(),
                                    true);
                        } catch (Throwable t) {
                            Log.exception(t);
                        }
                        myDone.set(true);
                        synchronized (cancelledLock) {
                            cancelledJobs.remove(request.runGuid);
                        }
                    }
                }
            }).start();
            return Response.ok(Crypto.encode(request.runGuid, CommonUtil.ip())).build();
        }
    }
    return null;
}

From source file:com.facebook.RequestTests.java

@LargeTest
public void testShareOpenGraphContentWithBadType() throws Exception {
    ShareOpenGraphObject ogObject = new ShareOpenGraphObject.Builder().putString("og:title", "a title")
            .putString("og:type", TEST_OG_OBJECT_TYPE).putString("og:description", "a description").build();

    ShareOpenGraphAction ogAction = new ShareOpenGraphAction.Builder()
            .setActionType(TEST_OG_ACTION_TYPE + "bad").putObject("test", ogObject).build();

    ShareOpenGraphContent content = new ShareOpenGraphContent.Builder().setAction(ogAction)
            .setPreviewPropertyName("test").build();

    final ShareApi shareApi = new ShareApi(content);
    final AtomicReference<String> actionId = new AtomicReference<>(null);
    final AtomicBoolean errorOccurred = new AtomicBoolean(false);

    getActivity().runOnUiThread(new Runnable() {
        @Override//from w w  w. j a  va  2  s .c  o m
        public void run() {
            shareApi.share(new FacebookCallback<Sharer.Result>() {
                @Override
                public void onSuccess(Sharer.Result result) {
                    actionId.set(result.getPostId());
                    notifyShareFinished();
                }

                @Override
                public void onCancel() {
                    notifyShareFinished();
                }

                @Override
                public void onError(FacebookException error) {
                    errorOccurred.set(true);
                    notifyShareFinished();
                }

                private void notifyShareFinished() {
                    synchronized (shareApi) {
                        shareApi.notifyAll();
                    }
                }
            });
        }
    });

    synchronized (shareApi) {
        shareApi.wait(REQUEST_TIMEOUT_MILLIS);
    }
    assertNull(actionId.get());
    assertTrue(errorOccurred.get());
}

From source file:com.indeed.lsmtree.recordcache.PersistentRecordCache.java

/**
 * Performs lookup for multiple keys and returns a streaming iterator to results.
 * Each element in the iterator is one of
 *  (1) an exception associated with a single lookup
 *  (2) a key value tuple//from   w  w  w . j  av a 2  s  .  c  o  m
 *
 * @param keys      lookup keys
 * @param progress  (optional) an AtomicInteger for tracking progress
 * @param skipped   (optional) an AtomicInteger for tracking missing keys
 * @return          iterator of lookup results
 */
public Iterator<Either<Exception, P2<K, V>>> getStreaming(final @Nonnull Iterator<K> keys,
        final @Nullable AtomicInteger progress, final @Nullable AtomicInteger skipped) {
    log.info("starting store lookups");
    LongArrayList addressList = new LongArrayList();
    int notFound = 0;
    while (keys.hasNext()) {
        final K key = keys.next();
        final Long address;
        try {
            address = index.get(key);
        } catch (IOException e) {
            log.error("error", e);
            return Iterators.singletonIterator(Left.<Exception, P2<K, V>>of(new IndexReadException(e)));
        }
        if (address != null) {
            addressList.add(address);
        } else {
            notFound++;
        }
    }
    if (progress != null)
        progress.addAndGet(notFound);
    if (skipped != null)
        skipped.addAndGet(notFound);
    log.info("store lookups complete, sorting addresses");

    final long[] addresses = addressList.elements();
    Arrays.sort(addresses, 0, addressList.size());

    log.info("initializing store lookup iterator");
    final BlockingQueue<Runnable> taskQueue = new ArrayBlockingQueue<Runnable>(100);
    final Iterator<List<Long>> iterable = Iterators.partition(addressList.iterator(), 1000);
    final ExecutorService primerThreads = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS, taskQueue,
            new NamedThreadFactory("store priming thread", true, log), new RejectedExecutionHandler() {
                @Override
                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                    try {
                        taskQueue.put(r);
                    } catch (InterruptedException e) {
                        log.error("error", e);
                        throw new RuntimeException(e);
                    }
                }
            });
    final BlockingQueue<List<Either<Exception, P2<K, V>>>> completionQueue = new ArrayBlockingQueue<List<Either<Exception, P2<K, V>>>>(
            10);
    final AtomicLong runningTasks = new AtomicLong(0);
    final AtomicBoolean taskSubmitterRunning = new AtomicBoolean(true);

    new Thread(new Runnable() {
        @Override
        public void run() {
            while (iterable.hasNext()) {
                runningTasks.incrementAndGet();
                final List<Long> addressesSublist = iterable.next();
                primerThreads.submit(new FutureTask<List<Either<Exception, P2<K, V>>>>(
                        new RecordLookupTask(addressesSublist)) {
                    @Override
                    protected void done() {
                        try {
                            final List<Either<Exception, P2<K, V>>> results = get();
                            if (progress != null) {
                                progress.addAndGet(results.size());
                            }
                            completionQueue.put(results);
                        } catch (InterruptedException e) {
                            log.error("error", e);
                            throw new RuntimeException(e);
                        } catch (ExecutionException e) {
                            log.error("error", e);
                            throw new RuntimeException(e);
                        }
                    }
                });
            }
            taskSubmitterRunning.set(false);
        }
    }, "RecordLookupTaskSubmitterThread").start();

    return new Iterator<Either<Exception, P2<K, V>>>() {

        Iterator<Either<Exception, P2<K, V>>> currentIterator;

        @Override
        public boolean hasNext() {
            if (currentIterator != null && currentIterator.hasNext())
                return true;
            while (taskSubmitterRunning.get() || runningTasks.get() > 0) {
                try {
                    final List<Either<Exception, P2<K, V>>> list = completionQueue.poll(1, TimeUnit.SECONDS);
                    if (list != null) {
                        log.debug("remaining: " + runningTasks.decrementAndGet());
                        currentIterator = list.iterator();
                        if (currentIterator.hasNext())
                            return true;
                    }
                } catch (InterruptedException e) {
                    log.error("error", e);
                    throw new RuntimeException(e);
                }
            }
            primerThreads.shutdown();
            return false;
        }

        @Override
        public Either<Exception, P2<K, V>> next() {
            return currentIterator.next();
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
}

From source file:org.elasticsearch.client.sniff.SnifferTests.java

/**
 * Test behaviour when a bunch of onFailure sniffing rounds are triggered in parallel. Each run will always
 * schedule a subsequent afterFailure round. Also, for each onFailure round that starts, the net scheduled round
 * (either afterFailure or ordinary) gets cancelled.
 *///from w w w.j a v  a 2s .c o  m
public void testSniffOnFailure() throws Exception {
    RestClient restClient = mock(RestClient.class);
    CountingHostsSniffer hostsSniffer = new CountingHostsSniffer();
    final AtomicBoolean initializing = new AtomicBoolean(true);
    final long sniffInterval = randomLongBetween(1, Long.MAX_VALUE);
    final long sniffAfterFailureDelay = randomLongBetween(1, Long.MAX_VALUE);
    int minNumOnFailureRounds = randomIntBetween(5, 10);
    final CountDownLatch initializingLatch = new CountDownLatch(1);
    final Set<Sniffer.ScheduledTask> ordinaryRoundsTasks = new CopyOnWriteArraySet<>();
    final AtomicReference<Future<?>> initializingFuture = new AtomicReference<>();
    final Set<Sniffer.ScheduledTask> onFailureTasks = new CopyOnWriteArraySet<>();
    final Set<Sniffer.ScheduledTask> afterFailureTasks = new CopyOnWriteArraySet<>();
    final AtomicBoolean onFailureCompleted = new AtomicBoolean(false);
    final CountDownLatch completionLatch = new CountDownLatch(1);
    final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    try {
        Scheduler scheduler = new Scheduler() {
            @Override
            public Future<?> schedule(final Sniffer.Task task, long delayMillis) {
                if (initializing.compareAndSet(true, false)) {
                    assertEquals(0L, delayMillis);
                    Future<?> future = executor.submit(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                task.run();
                            } finally {
                                //we need to make sure that the sniffer is initialized, so the sniffOnFailure
                                //call does what it needs to do. Otherwise nothing happens until initialized.
                                initializingLatch.countDown();
                            }
                        }
                    });
                    assertTrue(initializingFuture.compareAndSet(null, future));
                    return future;
                }
                if (delayMillis == 0L) {
                    Future<?> future = executor.submit(task);
                    onFailureTasks.add(new Sniffer.ScheduledTask(task, future));
                    return future;
                }
                if (delayMillis == sniffAfterFailureDelay) {
                    Future<?> future = scheduleOrSubmit(task);
                    afterFailureTasks.add(new Sniffer.ScheduledTask(task, future));
                    return future;
                }

                assertEquals(sniffInterval, delayMillis);
                assertEquals(sniffInterval, task.nextTaskDelay);

                if (onFailureCompleted.get() && onFailureTasks.size() == afterFailureTasks.size()) {
                    completionLatch.countDown();
                    return mock(Future.class);
                }

                Future<?> future = scheduleOrSubmit(task);
                ordinaryRoundsTasks.add(new Sniffer.ScheduledTask(task, future));
                return future;
            }

            private Future<?> scheduleOrSubmit(Sniffer.Task task) {
                if (randomBoolean()) {
                    return executor.schedule(task, randomLongBetween(0L, 200L), TimeUnit.MILLISECONDS);
                } else {
                    return executor.submit(task);
                }
            }

            @Override
            public void shutdown() {
            }
        };
        final Sniffer sniffer = new Sniffer(restClient, hostsSniffer, scheduler, sniffInterval,
                sniffAfterFailureDelay);
        assertTrue("timeout waiting for sniffer to get initialized",
                initializingLatch.await(1000, TimeUnit.MILLISECONDS));

        ExecutorService onFailureExecutor = Executors.newFixedThreadPool(randomIntBetween(5, 20));
        Set<Future<?>> onFailureFutures = new CopyOnWriteArraySet<>();
        try {
            //with tasks executing quickly one after each other, it is very likely that the onFailure round gets skipped
            //as another round is already running. We retry till enough runs get through as that's what we want to test.
            while (onFailureTasks.size() < minNumOnFailureRounds) {
                onFailureFutures.add(onFailureExecutor.submit(new Runnable() {
                    @Override
                    public void run() {
                        sniffer.sniffOnFailure();
                    }
                }));
            }
            assertThat(onFailureFutures.size(), greaterThanOrEqualTo(minNumOnFailureRounds));
            for (Future<?> onFailureFuture : onFailureFutures) {
                assertNull(onFailureFuture.get());
            }
            onFailureCompleted.set(true);
        } finally {
            onFailureExecutor.shutdown();
            onFailureExecutor.awaitTermination(1000, TimeUnit.MILLISECONDS);
        }

        assertFalse(initializingFuture.get().isCancelled());
        assertTrue(initializingFuture.get().isDone());
        assertNull(initializingFuture.get().get());

        assertTrue("timeout waiting for sniffing rounds to be completed",
                completionLatch.await(1000, TimeUnit.MILLISECONDS));
        assertThat(onFailureTasks.size(), greaterThanOrEqualTo(minNumOnFailureRounds));
        assertEquals(onFailureTasks.size(), afterFailureTasks.size());

        for (Sniffer.ScheduledTask onFailureTask : onFailureTasks) {
            assertFalse(onFailureTask.future.isCancelled());
            assertTrue(onFailureTask.future.isDone());
            assertNull(onFailureTask.future.get());
            assertTrue(onFailureTask.task.hasStarted());
            assertFalse(onFailureTask.task.isSkipped());
        }

        int cancelledTasks = 0;
        int completedTasks = onFailureTasks.size() + 1;
        for (Sniffer.ScheduledTask afterFailureTask : afterFailureTasks) {
            if (assertTaskCancelledOrCompleted(afterFailureTask)) {
                completedTasks++;
            } else {
                cancelledTasks++;
            }
        }

        assertThat(ordinaryRoundsTasks.size(), greaterThan(0));
        for (Sniffer.ScheduledTask task : ordinaryRoundsTasks) {
            if (assertTaskCancelledOrCompleted(task)) {
                completedTasks++;
            } else {
                cancelledTasks++;
            }
        }
        assertEquals(onFailureTasks.size(), cancelledTasks);

        assertEquals(completedTasks, hostsSniffer.runs.get());
        int setHostsRuns = hostsSniffer.runs.get() - hostsSniffer.failures.get() - hostsSniffer.emptyList.get();
        verify(restClient, times(setHostsRuns)).setHosts(Matchers.<HttpHost>anyVararg());
        verifyNoMoreInteractions(restClient);
    } finally {
        executor.shutdown();
        executor.awaitTermination(1000L, TimeUnit.MILLISECONDS);
    }
}

From source file:com.rapidminer.gui.new_plotter.engine.jfreechart.JFreeChartPlotEngine.java

public JFreeChartPlotEngine(PlotInstance plotInstanceForEngine, boolean zoomInOnSelection) {

    this.plotInstance = plotInstanceForEngine;
    updatingChart = new AtomicBoolean(false);

    chartPanel = new LinkAndBrushChartPanel(new JFreeChart(new CategoryPlot()), 50, 50, 50, 50,
            zoomInOnSelection);/*  w  w w .  j av a 2  s  .co m*/
    chartPanel.setMinimumDrawWidth(50);
    chartPanel.setMinimumDrawHeight(50);
    chartPanel.setMaximumDrawWidth(10000);
    chartPanel.setMaximumDrawHeight(10000);
    chartPanel.addMouseListener(popupMenuListener);

    subscribeAtPlotInstance(plotInstance);
}

From source file:com.adaptris.core.fs.NonDeletingFsConsumerTest.java

public void testRedmine481_SubDirInConsumeDirectory() throws Exception {
    String consumeDir = new GuidGenerator().safeUUID();
    File parentDir = FsHelper/*from  w w  w  .jav  a 2s .  co m*/
            .createFileReference(FsHelper.createUrlFromString(PROPERTIES.getProperty(BASE_KEY), true));
    File subDirectory = FsHelper.createFileReference(FsHelper.createUrlFromString(
            PROPERTIES.getProperty(BASE_KEY) + "/" + consumeDir + "/" + new GuidGenerator().safeUUID(), true));
    subDirectory.mkdirs();
    NonDeletingFsConsumer fs = createConsumer(consumeDir, "testRedmine481_SubDirInConsumeDirectory");
    fs.setReacquireLockBetweenMessages(true);
    AtomicBoolean pollFired = new AtomicBoolean(false);
    fs.setPoller(
            new FixedIntervalPoller(new TimeInterval(300L, TimeUnit.MILLISECONDS)).withPollerCallback(e -> {
                pollFired.set(true);
            }));
    MockMessageListener stub = new MockMessageListener(0);
    StandaloneConsumer sc = new StandaloneConsumer(fs);
    sc.registerAdaptrisMessageListener(stub);
    try {
        start(sc);
        waitForPollCallback(pollFired);
        assertEquals(true, subDirectory.exists());
        assertEquals(true, subDirectory.isDirectory());
    } finally {
        stop(sc);
        FileUtils.deleteQuietly(new File(parentDir, consumeDir));
    }
}