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

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

Introduction

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

Prototype

public final void set(int newValue) 

Source Link

Document

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

Usage

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

@Test
public void shouldOverrideAfterSuccess() throws Exception {
    final AtomicInteger called = new AtomicInteger(0);
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().afterSuccess(b -> called.set(1)).create();
    assertEquals(2,/*from   w  w w .j a  v  a  2s.co  m*/
            gremlinExecutor
                    .eval("1+1", null, new SimpleBindings(),
                            GremlinExecutor.LifeCycle.build().afterSuccess(b -> called.set(200)).create())
                    .get());

    // need to wait long enough for the callback to register
    Thread.sleep(500);

    assertEquals(200, called.get());
}

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

@Test
public void shouldEvalScriptWithMapBindingsAndLanguageThenConsume() throws Exception {
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().addEngineSettings("nashorn",
            Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), Collections.emptyMap())
            .create();//from   w w w . ja  va  2s  .  c  o m
    final Map<String, Object> b = new HashMap<>();
    b.put("x", 1);

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicInteger result = new AtomicInteger(0);
    assertEquals(2.0, gremlinExecutor.eval("1+x", "nashorn", b, r -> {
        result.set(((Double) r).intValue() * 2);
        latch.countDown();
    }).get());

    latch.await();
    assertEquals(4, result.get());
    gremlinExecutor.close();
}

From source file:metlos.executors.batch.BatchExecutorTest.java

public void testChangesInTaskCollectionPickedUpInRepetitions() throws Exception {
    final ConcurrentLinkedQueue<Runnable> tasks = new ConcurrentLinkedQueue<Runnable>();
    final AtomicInteger reportedNofTasks = new AtomicInteger();
    final CountDownLatch waitForTask2 = new CountDownLatch(2);
    final CountDownLatch waitForTask3 = new CountDownLatch(2);

    Runnable task1 = new Runnable() {
        @Override/*  ww  w.j  a v a2 s . com*/
        public void run() {
        }
    };

    Runnable task2 = new Runnable() {
        @Override
        public void run() {
            if (tasks.size() == 2) {
                reportedNofTasks.set(2);
                waitForTask2.countDown();
            }
        }
    };

    Runnable task3 = new Runnable() {
        @Override
        public void run() {
            if (tasks.size() == 3) {
                reportedNofTasks.set(3);
                waitForTask3.countDown();
            }
        }
    };

    BatchExecutor ex = getExecutor(10);

    tasks.add(task1);
    tasks.add(task2);

    ex.submitWithPreferedDurationAndFixedDelay(tasks, 0, 0, 0, TimeUnit.MILLISECONDS);

    //k, now the tasks should be running and there should be just 2 of them...
    //so we should be getting the value of "2" reported by the reportedNofTasks

    waitForTask2.countDown();
    waitForTask2.await();

    int currentReportedTasks = reportedNofTasks.get();

    assert currentReportedTasks == 2 : "We should be getting 2 tasks reported but are getting "
            + currentReportedTasks + " instead.";

    //k, now let's try updating the tasks collection... this should get picked up by the
    //repeated executions 
    tasks.add(task3);

    //now the reported nof tasks should change to 3. let's wait on it first to make sure the executor has had time to 
    //register the change.        
    waitForTask3.countDown();
    waitForTask3.await();

    currentReportedTasks = reportedNofTasks.get();

    assert currentReportedTasks == 3 : "We should be getting 3 tasks reported but are getting "
            + currentReportedTasks + " instead.";

    ex.shutdown();
}

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

@Test
public void shouldOverrideAfterFailure() throws Exception {
    final AtomicInteger called = new AtomicInteger(0);
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().afterFailure((b, t) -> called.set(1))
            .create();/*from www . j a va  2s .  c o m*/
    try {
        gremlinExecutor
                .eval("10/0", null, new SimpleBindings(),
                        GremlinExecutor.LifeCycle.build().afterFailure((b, t) -> called.set(200)).create())
                .get();
        fail("Should have failed with division by zero");
    } catch (Exception ignored) {

    }

    // need to wait long enough for the callback to register
    Thread.sleep(500);

    assertEquals(200, called.get());
}

From source file:org.springframework.integration.http.inbound.HttpRequestHandlingControllerTests.java

@Test
public void shutDown() throws Exception {
    DirectChannel requestChannel = new DirectChannel();
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    AbstractReplyProducingMessageHandler handler = new AbstractReplyProducingMessageHandler() {
        @Override//  w  w w. j  av a2  s.c o m
        protected Object handleRequestMessage(Message<?> requestMessage) {
            try {
                latch2.countDown();
                // hold up an active thread so we can verify the count and that it completes ok
                latch1.await(10, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            return requestMessage.getPayload().toString().toUpperCase();
        }
    };
    requestChannel.subscribe(handler);
    final HttpRequestHandlingController controller = new HttpRequestHandlingController(true);
    controller.setBeanFactory(mock(BeanFactory.class));
    controller.setRequestChannel(requestChannel);
    controller.setViewName("foo");
    controller.afterPropertiesSet();
    controller.start();

    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("POST");
    request.setContent("hello".getBytes());

    //request.setContentType("text/plain"); //Works in Spring 3.1.2.RELEASE but NOT in 3.0.7.RELEASE
    //Instead do:
    request.addHeader("Content-Type", "text/plain");

    MockHttpServletResponse response = new MockHttpServletResponse();
    final AtomicInteger active = new AtomicInteger();
    final AtomicBoolean expected503 = new AtomicBoolean();
    Executors.newSingleThreadExecutor().execute(() -> {
        try {
            // wait for the active thread
            latch2.await(10, TimeUnit.SECONDS);
        } catch (InterruptedException e1) {
            Thread.currentThread().interrupt();
        }
        // start the shutdown
        active.set(controller.beforeShutdown());
        try {
            MockHttpServletResponse response1 = new MockHttpServletResponse();
            controller.handleRequest(request, response1);
            expected503.set(response1.getStatus() == HttpStatus.SERVICE_UNAVAILABLE.value());
            latch1.countDown();
        } catch (Exception e) {
            LogFactory.getLog(getClass()).error("Async handleRequest failed", e);
        }
    });
    ModelAndView modelAndView = controller.handleRequest(request, response);
    // verify we get a 503 after shutdown starts
    assertEquals(1, active.get());
    assertTrue(expected503.get());
    // verify the active request still processed ok
    assertEquals("foo", modelAndView.getViewName());
    assertEquals(1, modelAndView.getModel().size());
    Object reply = modelAndView.getModel().get("reply");
    assertNotNull(reply);
    assertEquals("HELLO", reply);
}

From source file:dsfixgui.configs.DSFConfiguration.java

public void loadSettingsFromIniFile(String filePath) {

    File in = new File(filePath);
    String iniExt = DSF_FILES[1].substring(DSF_FILES[1].lastIndexOf('.'));
    int settingsChanged = 0;

    //Check for .ini file type
    if (iniExt.equals(filePath.substring(filePath.lastIndexOf('.')))) {
        try {//from w  ww  .j a va2 s .com
            fileInput = new Scanner(in);
            String line = " ";
            boolean verifiedIniFile = false;
            while (settingsChanged < TOTAL_SETTINGS && fileInput.hasNextLine()) {
                line = fileInput.nextLine();

                //Make sure it's a DSfix ini file and not just some random .ini
                if (settingsChanged == 0 && !verifiedIniFile && !line.equals(DSF_VERIFICATION)) {
                    ui.printConsole(in.getName() + INVALID_DSF_INI);
                    ui.printConsole(CONFIG_NOT_LOADED);
                    return;
                } else if (settingsChanged == 0 && !verifiedIniFile && line.equals(DSF_VERIFICATION)) {
                    verifiedIniFile = true;
                }

                if (line.length() > 1 && line.charAt(0) != '\n' && line.charAt(0) != '#') {
                    //Check for special settings that have special limitations
                    //This might actually be unecessary now (the mutator methods used to make changes based on certain limitations that I've since removed)
                    if (settingsChanged == 2 || settingsChanged == 3 || settingsChanged == 9) {
                        switch (settingsChanged) {
                        case 2:
                            setPresentWidth(
                                    Integer.parseInt(line.substring(line.indexOf(' ') + 1, line.length())));
                            break;
                        case 3:
                            setPresentHeight(
                                    Integer.parseInt(line.substring(line.indexOf(' ') + 1, line.length())));
                            break;
                        case 9:
                            setDOFOverride(
                                    Integer.parseInt(line.substring(line.indexOf(' ') + 1, line.length())));
                            break;
                        default:
                            break;
                        }
                        //Check for int valued setting
                    } else if (INT_VALUE_NAMES[settingsChanged] != null) {
                        //Change int value
                        AtomicInteger intVal = (AtomicInteger) settings.get(settingsChanged);
                        intVal.set(Integer.parseInt(line.substring(line.indexOf(' ') + 1, line.length())));
                        //Check for StringBuilder valued setting
                    } else {
                        //Change StringBuilder value
                        StringBuilder stringVal = (StringBuilder) settings.get(settingsChanged);
                        stringVal.replace(0, stringVal.length(), ("" + line.substring(line.indexOf(' ') + 1)));
                        if (settingsChanged == 11) {
                        }
                    }
                    settingsChanged++;
                }
            }

        } catch (FileNotFoundException ex) {
            //Logger.getLogger(DSFConfiguration.class.getName()).log(Level.SEVERE, null, ex);
            ui.printConsole(in.getName() + DSFGUI_FILE_NOT_FOUND);
        }
    } else {
        ui.printConsole(in.getName() + INVALID_FILETYPE_ERR + iniExt);
        ui.printConsole(CONFIG_NOT_LOADED);
    }

    if (settingsChanged != TOTAL_SETTINGS) {
        ui.printConsole(CONFIG_PARTIALLY_LOADED);
        ui.resetDSFConfigDefaults();
    } else {
        ui.printConsole(SETTINGS_LOADED);
    }

    if (fileInput != null) {
        fileInput.close();
    }

    if (dofOverrideResolution.get() == renderHeight.get() && presentWidth.get() == renderWidth.get()
            && presentHeight.get() == renderHeight.get() && disableDofScaling.get() == 1
            && dofBlurAmount.toString().equals("o")) {
        disableDOF = true;
    } else {
        disableDOF = false;
    }

    initSettingsList();
}

From source file:com.jivesoftware.os.amza.deployable.Main.java

public void run(String[] args) throws Exception {

    String hostname = args[0];//from www .  j a va  2  s .c  o  m
    String clusterName = (args.length > 1 ? args[1] : "unnamed");
    String hostPortPeers = (args.length > 2 ? args[2] : null);

    int port = Integer.parseInt(System.getProperty("amza.port", "1175"));
    String multicastGroup = System.getProperty("amza.discovery.group", "225.4.5.6");
    int multicastPort = Integer.parseInt(System.getProperty("amza.discovery.port", "1223"));

    String logicalName = System.getProperty("amza.logicalName", hostname + ":" + port);
    String datacenter = System.getProperty("host.datacenter", "unknownDatacenter");
    String rack = System.getProperty("host.rack", "unknownRack");

    RingMember ringMember = new RingMember(logicalName);
    RingHost ringHost = new RingHost(datacenter, rack, hostname, port);

    // todo need a better way to create writer id.
    int writerId = Integer.parseInt(System.getProperty("amza.id", String.valueOf(new Random().nextInt(512))));

    SnowflakeIdPacker idPacker = new SnowflakeIdPacker();
    JiveEpochTimestampProvider timestampProvider = new JiveEpochTimestampProvider();
    final TimestampedOrderIdProvider orderIdProvider = new OrderIdProviderImpl(
            new ConstantWriterIdProvider(writerId), idPacker, timestampProvider);

    final ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(SerializationFeature.INDENT_OUTPUT, false);

    final AmzaServiceConfig amzaServiceConfig = new AmzaServiceConfig();
    final AmzaStats amzaSystemStats = new AmzaStats();
    final AmzaStats amzaStats = new AmzaStats();
    final SickThreads sickThreads = new SickThreads();
    final SickPartitions sickPartitions = new SickPartitions();

    AtomicInteger systemRingSize = new AtomicInteger(-1);
    amzaServiceConfig.workingDirectories = System.getProperty("amza.working.dirs", "./data1,./data2,./data3")
            .split(",");
    amzaServiceConfig.systemRingSize = Integer.parseInt(System.getProperty("amza.system.ring.size", "-1"));
    if (amzaServiceConfig.systemRingSize > 0) {
        systemRingSize.set(amzaServiceConfig.systemRingSize);
    }

    AmzaInterner amzaInterner = new AmzaInterner();

    PartitionPropertyMarshaller partitionPropertyMarshaller = new PartitionPropertyMarshaller() {
        @Override
        public PartitionProperties fromBytes(byte[] bytes) {
            try {
                return mapper.readValue(bytes, PartitionProperties.class);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }

        @Override
        public byte[] toBytes(PartitionProperties partitionProperties) {
            try {
                return mapper.writeValueAsBytes(partitionProperties);
            } catch (JsonProcessingException ex) {
                throw new RuntimeException(ex);
            }
        }
    };

    //  hmmm
    LABPointerIndexConfig labConfig = BindInterfaceToConfiguration.bindDefault(LABPointerIndexConfig.class);
    labConfig.setLeapCacheMaxCapacity(
            Integer.parseInt(System.getProperty("amza.leap.cache.max.capacity", "1000000")));

    BinaryPrimaryRowMarshaller primaryRowMarshaller = new BinaryPrimaryRowMarshaller(); // hehe you cant change this :)
    BinaryHighwaterRowMarshaller highwaterRowMarshaller = new BinaryHighwaterRowMarshaller(amzaInterner);

    AtomicReference<Callable<RingTopology>> topologyProvider = new AtomicReference<>(); // bit of a hack

    InstanceDescriptor instanceDescriptor = new InstanceDescriptor(datacenter, rack, "", "", "", "", "", "", "",
            "", 0, "", "", "", 0L, true);
    ConnectionDescriptorsProvider connectionsProvider = (connectionDescriptorsRequest,
            expectedReleaseGroup) -> {
        try {
            RingTopology systemRing = topologyProvider.get().call();
            List<ConnectionDescriptor> descriptors = Lists.newArrayList(Iterables.transform(systemRing.entries,
                    input -> new ConnectionDescriptor(instanceDescriptor, false, false,
                            new HostPort(input.ringHost.getHost(), input.ringHost.getPort()),
                            Collections.emptyMap(), Collections.emptyMap())));
            return new ConnectionDescriptorsResponse(200, Collections.emptyList(), "", descriptors,
                    connectionDescriptorsRequest.getRequestUuid());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    };
    TenantsServiceConnectionDescriptorProvider<String> connectionPoolProvider = new TenantsServiceConnectionDescriptorProvider<>(
            Executors.newScheduledThreadPool(1), "", connectionsProvider, "", "", 10_000); // TODO config
    connectionPoolProvider.start();

    TenantAwareHttpClient<String> httpClient = new TenantRoutingHttpClientInitializer<String>(null)
            .builder(connectionPoolProvider, new HttpDeliveryClientHealthProvider("", null, "", 5000, 100))
            .deadAfterNErrors(10).checkDeadEveryNMillis(10_000).maxConnections(1_000)
            .socketTimeoutInMillis(60_000).build(); //TODO expose to conf

    AvailableRowsTaker availableRowsTaker = new HttpAvailableRowsTaker(httpClient, amzaInterner, mapper); // TODO config
    AquariumStats aquariumStats = new AquariumStats();

    AmzaService amzaService = new AmzaServiceInitializer().initialize(amzaServiceConfig, amzaInterner,
            aquariumStats, amzaSystemStats, amzaStats,
            new HealthTimer(CountersAndTimers.getOrCreate("quorumLatency"), "quorumLatency",
                    new NoOpHealthChecker<>("quorumLatency")),
            () -> amzaServiceConfig.systemRingSize, sickThreads, sickPartitions, primaryRowMarshaller,
            highwaterRowMarshaller, ringMember, ringHost, Collections.emptySet(), orderIdProvider, idPacker,
            partitionPropertyMarshaller, (workingIndexDirectories, indexProviderRegistry,
                    ephemeralRowIOProvider, persistentRowIOProvider, partitionStripeFunction) -> {
                indexProviderRegistry
                        .register(
                                new BerkeleyDBWALIndexProvider(BerkeleyDBWALIndexProvider.INDEX_CLASS_NAME,
                                        partitionStripeFunction, workingIndexDirectories),
                                persistentRowIOProvider);

                indexProviderRegistry.register(new LABPointerIndexWALIndexProvider(amzaInterner, labConfig,
                        Executors.newCachedThreadPool(), Executors.newCachedThreadPool(),
                        Executors.newCachedThreadPool(), Executors.newCachedThreadPool(),
                        LABPointerIndexWALIndexProvider.INDEX_CLASS_NAME, partitionStripeFunction,
                        workingIndexDirectories), persistentRowIOProvider);
            }, availableRowsTaker, () -> {
                return new HttpRowsTaker("system", amzaStats, httpClient, mapper, amzaInterner,
                        Executors.newSingleThreadExecutor(), Executors.newCachedThreadPool());
            }, () -> {
                return new HttpRowsTaker("striped", amzaStats, httpClient, mapper, amzaInterner,
                        Executors.newSingleThreadExecutor(), Executors.newCachedThreadPool());
            }, Optional.absent(), (changes) -> {
            }, (threadCount, name) -> {
                return Executors.newCachedThreadPool();
            });

    topologyProvider.set(() -> amzaService.getRingReader().getRing(AmzaRingReader.SYSTEM_RING, -1));

    TailAtScaleStrategy tailAtScaleStrategy = new TailAtScaleStrategy(
            BoundedExecutor.newBoundedExecutor(1024, "tas"), 100, // TODO config
            95, // TODO config
            1000 // TODO config
    );

    AmzaClientProvider<HttpClient, HttpClientException> clientProvider = new AmzaClientProvider<>(
            new HttpPartitionClientFactory(),
            new HttpPartitionHostsProvider(httpClient, tailAtScaleStrategy, mapper),
            new RingHostHttpClientProvider(httpClient), BoundedExecutor.newBoundedExecutor(1024, "amza-client"),
            10_000, //TODO expose to conf
            -1, -1);

    final JerseyEndpoints jerseyEndpoints = new JerseyEndpoints().addEndpoint(AmzaEndpoints.class)
            .addInjectable(AmzaService.class, amzaService).addEndpoint(AmzaReplicationRestEndpoints.class)
            .addInjectable(AmzaInstance.class, amzaService).addEndpoint(AmzaClientRestEndpoints.class)
            .addInjectable(AmzaInterner.class, amzaInterner).addInjectable(ObjectMapper.class, mapper)
            .addInjectable(AmzaClientService.class, new AmzaClientService(amzaService.getRingReader(),
                    amzaService.getRingWriter(), amzaService));

    new AmzaUIInitializer().initialize(clusterName, ringHost, amzaService, clientProvider, aquariumStats,
            amzaStats, timestampProvider, idPacker, amzaInterner, new AmzaUIInitializer.InjectionCallback() {
                @Override
                public void addEndpoint(Class clazz) {
                    System.out.println("Adding endpoint=" + clazz);
                    jerseyEndpoints.addEndpoint(clazz);
                }

                @Override
                public void addInjectable(Class clazz, Object instance) {
                    System.out.println("Injecting " + clazz + " " + instance);
                    jerseyEndpoints.addInjectable(clazz, instance);
                }

                @Override
                public void addSessionAuth(String... paths) throws Exception {
                    System.out.println("Ignoring session auth request for paths: " + Arrays.toString(paths));
                }
            });

    InitializeRestfulServer initializeRestfulServer = new InitializeRestfulServer(false, port, "AmzaNode",
            false, null, null, null, 128, 10000);
    initializeRestfulServer.addClasspathResource("/resources");
    initializeRestfulServer.addContextHandler("/", jerseyEndpoints);
    RestfulServer restfulServer = initializeRestfulServer.build();
    restfulServer.start();

    System.out.println("-----------------------------------------------------------------------");
    System.out.println("|      Jetty Service Online");
    System.out.println("-----------------------------------------------------------------------");

    amzaService.start(ringMember, ringHost);

    System.out.println("-----------------------------------------------------------------------");
    System.out.println("|      Amza Service Online");
    System.out.println("-----------------------------------------------------------------------");

    if (clusterName != null) {
        if (hostPortPeers != null) {
            System.out.println("-----------------------------------------------------------------------");
            System.out.println("|     Amza Service is in manual Discovery mode. Cluster Name:" + clusterName);
            String[] peers = hostPortPeers.split(",");
            for (String peer : peers) {
                String[] hostPort = peer.trim().split(":");
                if (hostPort.length != 2 && hostPort.length != 3) {
                    System.out.println("|     Malformed peer:" + peer
                            + " expected form: <host>:<port> or <logicalName>:<host>:<port>");
                } else {
                    String peerLogicalName = (hostPort.length == 2) ? hostPort[0] + ":" + hostPort[1]
                            : hostPort[0];
                    String peerHostname = (hostPort.length == 2) ? hostPort[0] : hostPort[1];
                    String peerPort = (hostPort.length == 2) ? hostPort[1] : hostPort[2];

                    RingMember peerRingMember = new RingMember(peerLogicalName);
                    RingHost peerRingHost = new RingHost("unknown", "unknown", peerHostname,
                            Integer.parseInt(peerPort));

                    System.out.println("|     Adding ringMember:" + peerRingMember + " on host:" + peerRingHost
                            + " to cluster: " + clusterName);
                    amzaService.getRingWriter().register(peerRingMember, peerRingHost, writerId, false);
                }
            }
            systemRingSize.set(1 + peers.length);
            System.out.println("-----------------------------------------------------------------------");
        } else {
            AmzaDiscovery amzaDiscovery = new AmzaDiscovery(amzaService.getRingReader(),
                    amzaService.getRingWriter(), clusterName, multicastGroup, multicastPort, systemRingSize);
            amzaDiscovery.start();
            System.out.println("-----------------------------------------------------------------------");
            System.out.println("|      Amza Service Discovery Online: Cluster Name:" + clusterName);
            System.out.println("-----------------------------------------------------------------------");
        }
    } else {
        System.out.println("-----------------------------------------------------------------------");
        System.out.println("|     Amza Service is in manual Discovery mode.  No cluster name was specified");
        System.out.println("-----------------------------------------------------------------------");
    }
}

From source file:io.fabric8.kubernetes.client.dsl.internal.RollingUpdater.java

/**
 * Lets wait until there are enough Ready pods of the given RC
 *///from   ww w  .java2s.c  o m
private void waitUntilPodsAreReady(final T obj, final String namespace, final int requiredPodCount) {
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    final AtomicInteger podCount = new AtomicInteger(0);

    final Runnable readyPodsPoller = new Runnable() {
        public void run() {
            PodList podList = listSelectedPods(obj);
            int count = 0;
            List<Pod> items = podList.getItems();
            for (Pod item : items) {
                for (PodCondition c : item.getStatus().getConditions()) {
                    if (c.getType().equals("Ready") && c.getStatus().equals("True")) {
                        count++;
                    }
                }
            }
            podCount.set(count);
            if (count == requiredPodCount) {
                countDownLatch.countDown();
            }
        }
    };

    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    ScheduledFuture poller = executor.scheduleWithFixedDelay(readyPodsPoller, 0, 1, TimeUnit.SECONDS);
    ScheduledFuture logger = executor.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            LOG.debug("Only {}/{} pod(s) ready for {}: {} in namespace: {} seconds so waiting...",
                    podCount.get(), requiredPodCount, obj.getKind(), obj.getMetadata().getName(), namespace);
        }
    }, 0, loggingIntervalMillis, TimeUnit.MILLISECONDS);
    try {
        countDownLatch.await(rollingTimeoutMillis, TimeUnit.MILLISECONDS);
        executor.shutdown();
    } catch (InterruptedException e) {
        poller.cancel(true);
        logger.cancel(true);
        executor.shutdown();
        LOG.warn(
                "Only {}/{} pod(s) ready for {}: {} in namespace: {}  after waiting for {} seconds so giving up",
                podCount.get(), requiredPodCount, obj.getKind(), obj.getMetadata().getName(), namespace,
                TimeUnit.MILLISECONDS.toSeconds(rollingTimeoutMillis));
    }
}

From source file:org.apache.hadoop.hbase.client.TestAsyncTable.java

@Test
public void testCheckAndPut() throws InterruptedException, ExecutionException {
    AsyncTableBase table = getTable.get();
    AtomicInteger successCount = new AtomicInteger(0);
    AtomicInteger successIndex = new AtomicInteger(-1);
    int count = 10;
    CountDownLatch latch = new CountDownLatch(count);
    IntStream.range(0, count)/*from  ww w  .j  a v  a 2  s .  c  o  m*/
            .forEach(
                    i -> table
                            .checkAndPut(row, FAMILY, QUALIFIER, null,
                                    new Put(row).addColumn(FAMILY, QUALIFIER, concat(VALUE, i)))
                            .thenAccept(x -> {
                                if (x) {
                                    successCount.incrementAndGet();
                                    successIndex.set(i);
                                }
                                latch.countDown();
                            }));
    latch.await();
    assertEquals(1, successCount.get());
    String actual = Bytes.toString(table.get(new Get(row)).get().getValue(FAMILY, QUALIFIER));
    assertTrue(actual.endsWith(Integer.toString(successIndex.get())));
}

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 {/*from  w  ww .jav a 2s.  com*/
            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();
}