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.dyn.core.handler.AnnotationHandlerMethodResolver.java

@Override
public boolean supports(final Class<?> aClass) {
    boolean classLevelAnno = (null != AnnotationUtils.findAnnotation(aClass, Handler.class));
    final AtomicBoolean hasHandlerMethod = new AtomicBoolean(false);
    Class<?> clazz = aClass;
    while (null != clazz && clazz != Object.class) {
        ReflectionUtils.doWithMethods(clazz, new ReflectionUtils.MethodCallback() {
            @Override//  w w w.j  a va 2s .  co  m
            public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                if (!hasHandlerMethod.get()) {
                    hasHandlerMethod.set(true);
                }
            }
        }, Handlers.USER_METHODS);
        clazz = clazz.getSuperclass();
    }

    return (hasHandlerMethod.get() || classLevelAnno);
}

From source file:net.sourceforge.ganttproject.io.CsvImportTest.java

public void testTwoGroups() throws Exception {
    String header1 = "A, B";
    String data1 = "a1, b1";
    final AtomicBoolean wasCalled1 = new AtomicBoolean(false);
    GanttCSVOpen.RecordGroup recordGroup1 = new GanttCSVOpen.RecordGroup("AB",
            ImmutableSet.<String>of("A", "B")) {
        @Override/*from   w  w  w.java2s . c  om*/
        protected boolean doProcess(CSVRecord record) {
            assertEquals("a1", record.get("A"));
            assertEquals("b1", record.get("B"));
            wasCalled1.set(true);
            return true;
        }
    };

    String header2 = "C, D, E";
    String data2 = "c1, d1, e1";
    final AtomicBoolean wasCalled2 = new AtomicBoolean(false);
    GanttCSVOpen.RecordGroup recordGroup2 = new GanttCSVOpen.RecordGroup("CDE",
            ImmutableSet.<String>of("C", "D", "E")) {
        @Override
        protected boolean doProcess(CSVRecord record) {
            assertEquals("c1", record.get("C"));
            assertEquals("d1", record.get("D"));
            assertEquals("e1", record.get("E"));
            wasCalled2.set(true);
            return true;
        }
    };
    GanttCSVOpen importer = new GanttCSVOpen(
            createSupplier(Joiner.on('\n').join(header1, data1, "", header2, data2)), recordGroup1,
            recordGroup2);
    importer.load();
    assertTrue(wasCalled1.get() && wasCalled2.get());
}

From source file:com.alibaba.wasp.executor.TestExecutorService.java

@Test
public void testExecutorService() throws Exception {
    int maxThreads = 5;
    int maxTries = 10;
    int sleepInterval = 10;

    Server mockedServer = mock(Server.class);
    when(mockedServer.getConfiguration()).thenReturn(conf);

    // Start an executor service pool with max 5 threads
    ExecutorService executorService = new ExecutorService("unit_test");
    executorService.startExecutorService(ExecutorType.MASTER_SERVER_OPERATIONS, maxThreads);

    Executor executor = executorService.getExecutor(ExecutorType.MASTER_SERVER_OPERATIONS);
    ThreadPoolExecutor pool = executor.threadPoolExecutor;

    // Assert no threads yet
    assertEquals(0, pool.getPoolSize());

    AtomicBoolean lock = new AtomicBoolean(true);
    AtomicInteger counter = new AtomicInteger(0);

    // Submit maxThreads executors.
    for (int i = 0; i < maxThreads; i++) {
        executorService.submit(new TestEventHandler(mockedServer, EventType.M_SERVER_SHUTDOWN, lock, counter));
    }/*from  w  w  w.j  a v  a 2 s .  c  om*/

    // The TestEventHandler will increment counter when it starts.
    int tries = 0;
    while (counter.get() < maxThreads && tries < maxTries) {
        LOG.info("Waiting for all event handlers to start...");
        Thread.sleep(sleepInterval);
        tries++;
    }

    // Assert that pool is at max threads.
    assertEquals(maxThreads, counter.get());
    assertEquals(maxThreads, pool.getPoolSize());

    ExecutorStatus status = executor.getStatus();
    assertTrue(status.queuedEvents.isEmpty());
    assertEquals(5, status.running.size());
    checkStatusDump(status);

    // Now interrupt the running Executor
    synchronized (lock) {
        lock.set(false);
        lock.notifyAll();
    }

    // Executor increments counter again on way out so.... test that happened.
    while (counter.get() < (maxThreads * 2) && tries < maxTries) {
        System.out.println("Waiting for all event handlers to finish...");
        Thread.sleep(sleepInterval);
        tries++;
    }

    assertEquals(maxThreads * 2, counter.get());
    assertEquals(maxThreads, pool.getPoolSize());

    // Add more than the number of threads items.
    // Make sure we don't get RejectedExecutionException.
    for (int i = 0; i < (2 * maxThreads); i++) {
        executorService.submit(new TestEventHandler(mockedServer, EventType.M_SERVER_SHUTDOWN, lock, counter));
    }
    // Now interrupt the running Executor
    synchronized (lock) {
        lock.set(false);
        lock.notifyAll();
    }

    // Make sure threads are still around even after their timetolive expires.
    Thread.sleep(ExecutorService.Executor.keepAliveTimeInMillis * 2);
    assertEquals(maxThreads, pool.getPoolSize());

    executorService.shutdown();

    assertEquals(0, executorService.getAllExecutorStatuses().size());

    // Test that submit doesn't throw NPEs
    executorService.submit(new TestEventHandler(mockedServer, EventType.M_SERVER_SHUTDOWN, lock, counter));
}

From source file:com.spectralogic.ds3client.helpers.FileObjectGetter_Test.java

@Test
public void testThatFileReportsAsRegularOnWindows() throws IOException, InterruptedException {
    Assume.assumeTrue(Platform.isWindows());

    final String tempPathPrefix = null;
    final Path tempDirectory = Files.createTempDirectory(Paths.get("."), tempPathPrefix);

    final String A_FILE_NAME = "aFile.txt";

    final AtomicBoolean caughtException = new AtomicBoolean(false);

    try {/*ww  w  .j  a va  2  s. c  o m*/
        Files.createFile(Paths.get(tempDirectory.toString(), A_FILE_NAME));
        new FileObjectGetter(tempDirectory).buildChannel(A_FILE_NAME);
    } catch (final UnrecoverableIOException e) {
        assertTrue(e.getMessage().contains(A_FILE_NAME));
        caughtException.set(true);
    } finally {
        FileUtils.deleteDirectory(tempDirectory.toFile());
    }

    assertFalse(caughtException.get());
}

From source file:interactivespaces.util.web.WebSocketTest.java

@Test
public void testWebSocketCommunication() throws Exception {
    final String dataKey = "message";

    final CountDownLatch clientOpenning = new CountDownLatch(1);
    final CountDownLatch clientClosing = new CountDownLatch(1);

    final AtomicBoolean onConnectCalledServer = new AtomicBoolean(false);
    final AtomicBoolean onCloseCalledServer = new AtomicBoolean(false);

    final AtomicReference<WebServerWebSocketHandler> serverHandler = new AtomicReference<WebServerWebSocketHandler>();

    int port = 8082;
    String webSocketUriPrefix = "websockettest";

    URI uri = new URI(String.format("ws://127.0.0.1:%d/%s", port, webSocketUriPrefix));

    final List<Integer> serverReceivedList = Lists.newArrayList();
    final List<Integer> clientReceivedList = Lists.newArrayList();
    List<Integer> serverSentList = Lists.newArrayList();
    List<Integer> clientSentList = Lists.newArrayList();
    Random random = new Random(System.currentTimeMillis());

    for (int i = 0; i < 100; i++) {
        clientSentList.add(random.nextInt());
        serverSentList.add(random.nextInt());
    }//  ww w  . ja v  a 2  s. c o  m

    NettyWebServer server = new NettyWebServer(threadPool, log);
    server.setServerName("test-server");
    server.setPort(port);
    server.setWebSocketHandlerFactory(webSocketUriPrefix, new WebServerWebSocketHandlerFactory() {

        @Override
        public WebServerWebSocketHandler newWebSocketHandler(WebSocketConnection connection) {
            WebServerWebSocketHandler handler = new WebServerWebSocketHandlerSupport(connection) {

                @Override
                public void onReceive(Object data) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> d = (Map<String, Object>) data;

                    serverReceivedList.add((Integer) d.get(dataKey));
                }

                @Override
                public void onConnect() {
                    onConnectCalledServer.set(true);
                }

                @Override
                public void onClose() {
                    onCloseCalledServer.set(true);
                }
            };

            serverHandler.set(handler);

            return handler;
        }
    });
    server.startup();

    Thread.sleep(2000);

    WebSocketHandler clientHandler = new WebSocketHandler() {

        @Override
        public void onConnect() {
            clientOpenning.countDown();
        }

        @Override
        public void onClose() {
            clientClosing.countDown();
        }

        @Override
        public void onReceive(Object data) {
            @SuppressWarnings("unchecked")
            Map<String, Object> d = (Map<String, Object>) data;

            clientReceivedList.add((Integer) d.get(dataKey));
        }
    };

    NettyWebSocketClient client = new NettyWebSocketClient(uri, clientHandler, threadPool, log);
    client.startup();

    Assert.assertTrue(clientOpenning.await(10, TimeUnit.SECONDS));

    Assert.assertTrue(client.isOpen());

    Map<String, Object> data = Maps.newHashMap();
    for (Integer i : clientSentList) {
        data.put("message", i);
        client.writeDataAsJson(data);
    }

    for (Integer i : serverSentList) {
        data.put("message", i);
        serverHandler.get().sendJson(data);
    }

    client.ping();

    client.shutdown();

    Assert.assertTrue(clientClosing.await(10, TimeUnit.SECONDS));

    server.shutdown();

    Assert.assertEquals(clientSentList, serverReceivedList);
    Assert.assertEquals(serverSentList, clientReceivedList);
    Assert.assertTrue(onConnectCalledServer.get());
    Assert.assertTrue(onCloseCalledServer.get());
}

From source file:tools.datasync.db2db.net.TCPConnection.java

public TCPConnection() {
    logger.info("Creating TCP Connection service...");
    handlers = new ArrayList<SyncDataHandler>();
    connectionLock = new ReentrantLock();
    isConnected = new AtomicBoolean(false);
}

From source file:com.pinterest.pinlater.backends.mysql.MySQLDataSources.java

public MySQLDataSources(PropertiesConfiguration configuration, String host, int port, String user,
        String passwd, boolean dequeueOnly) {
    int numGeneralConnections = configuration.getInt("BACKEND_CONNECTIONS_PER_SHARD");
    int generalSocketTimeoutMillis = (int) TimeUnit.SECONDS
            .toMillis(configuration.getInt("BACKEND_SOCKET_TIMEOUT_SECONDS"));
    int numMonitorConnections = configuration.getInt("MONITOR_CONNECTIONS_PER_SHARD", 3);
    int monitorSocketTimeoutMillis = (int) TimeUnit.SECONDS
            .toMillis(configuration.getInt("MONITOR_SOCKET_TIMEOUT_SECONDS", 10));
    int maxWaitMillis = configuration.getInt("BACKEND_CONNECTION_MAX_WAIT_MILLIS");
    this.generalDataSource = createDataSource(host, port, user, passwd, numGeneralConnections, maxWaitMillis,
            generalSocketTimeoutMillis);
    this.monitorDataSource = createDataSource(host, port, user, passwd, numMonitorConnections, maxWaitMillis,
            monitorSocketTimeoutMillis);
    this.host = host;
    this.port = port;
    this.user = user;
    this.passwd = passwd;
    this.dequeueOnly = new AtomicBoolean(dequeueOnly);
}

From source file:io.cloudslang.engine.queue.services.recovery.ExecutionRecoveryServiceImpl.java

protected void assignRecoveredMessages() {
    if (logger.isDebugEnabled())
        logger.debug("Reassigning recovered messages is being started");
    long time = System.currentTimeMillis();
    final AtomicBoolean shouldContinue = new AtomicBoolean(true);
    while (shouldContinue.get()) {
        List<ExecutionMessage> messages = executionQueueService.readMessagesByStatus(DEFAULT_POLL_SIZE,
                ExecStatus.RECOVERED);/*from www  .  j ava  2s . co m*/
        messageRecoveryService.enqueueMessages(messages, ExecStatus.PENDING);
        shouldContinue.set(messages != null && messages.size() == DEFAULT_POLL_SIZE);
    }
    if (logger.isDebugEnabled())
        logger.debug(
                "Reassigning recovered messages is done in " + (System.currentTimeMillis() - time) + " ms");
}

From source file:com.opinionlab.woa.WallOfAwesome.java

private static SockJSHandler makeEventStream(Vertx vertx) {
    final SockJSHandlerOptions options = new SockJSHandlerOptions().setHeartbeatInterval(2000);
    final SockJSHandler sockJSHandler = SockJSHandler.create(vertx, options);

    sockJSHandler.socketHandler(socket -> {
        final AtomicInteger openCount = new AtomicInteger();
        final AtomicBoolean running = new AtomicBoolean(true);
        LOGGER.info(format("[OPEN] Sockets: %d", openCount.incrementAndGet()));

        socket.endHandler(aVoid -> {//  w  w  w.  j  a  va2  s.co m
            running.set(false);
            LOGGER.info(format("[CLOSE] Sockets: %d", openCount.decrementAndGet()));
        });

        socket.handler(buffer -> {
            String command = buffer.toString();
            if ("purge".equals(command)) {
                EXECUTOR.execute(() -> {
                    try {
                        AwesomeImap.purge(s -> socket.write(buffer(objectToJson(
                                HashTreePMap.empty().plus("deleted", true).plus("id", s.getId()), NO_TYPES))));
                    } catch (NoSuchProviderException e) {
                        LOGGER.error("Could not purge messages", e);
                    }
                });
            } else {
                LOGGER.error(format("Unknown command: %s", command));
            }
        });

        try {
            final AtomicReference<Date> latestDate = new AtomicReference<>(new Date(0));

            Consumer<Awesome> publishAwesome = awesome -> {
                socket.write(buffer(objectToJson(awesome, NO_TYPES)));

                final Date receivedDate = awesome.getReceivedDate();
                if (latestDate.get().before(receivedDate)) {
                    latestDate.set(receivedDate);
                }
            };
            AwesomeImap.fetchAwesome().forEach(publishAwesome);

            EXECUTOR.execute(() -> {
                LOGGER.info("Polling started.");
                try {
                    while (running.get()) {
                        AwesomeImap.fetchAwesomeSince(latestDate.get()).forEach(publishAwesome);
                        Thread.sleep(1000);
                    }
                } catch (Throwable t) {
                    running.set(false);
                    socket.close();
                    LOGGER.error("Polling ended ABNORMALLY", t);
                } finally {
                    LOGGER.info("Polling ended normally.");
                }
            });
        } catch (MessagingException e) {
            LOGGER.error("Unable to fetch messages.", e);
        }
    });
    return sockJSHandler;
}

From source file:com.twitter.hbc.httpclient.BasicClient.java

public BasicClient(String name, Hosts hosts, StreamingEndpoint endpoint, Authentication auth,
        boolean enableGZip, HosebirdMessageProcessor processor, ReconnectionManager reconnectionManager,
        RateTracker rateTracker, ExecutorService executorService, @Nullable BlockingQueue<Event> eventsQueue,
        HttpParams params, SchemeRegistry schemeRegistry) {
    Preconditions.checkNotNull(auth);//  w w  w .j a va 2  s  .c om
    HttpClient client;
    if (enableGZip) {
        client = new RestartableHttpClient(auth, enableGZip, params, schemeRegistry);
    } else {
        DefaultHttpClient defaultClient = new DefaultHttpClient(
                new PoolingClientConnectionManager(schemeRegistry), params);

        /** Set auth **/
        auth.setupConnection(defaultClient);
        client = defaultClient;
    }

    this.canRun = new AtomicBoolean(true);
    this.executorService = executorService;
    this.clientBase = new ClientBase(name, client, hosts, endpoint, auth, processor, reconnectionManager,
            rateTracker, eventsQueue);
}