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

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

Introduction

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

Prototype

public final boolean get() 

Source Link

Document

Returns the current value, with memory effects as specified by VarHandle#getVolatile .

Usage

From source file:com.streamsets.pipeline.lib.jdbc.multithread.TestMultithreadedTableProvider.java

@Test
public void tableAndSchemasFinished() throws InterruptedException, StageException {
    String schema1 = "schema1";
    String table1Name = "table1";
    String table2Name = "table2";
    String schema2 = "schema2";
    String table3Name = "table3";

    String offsetCol = null;//  www .jav a 2 s .com
    final String partitionSize = null;
    int maxActivePartitions = 0;
    int threadNumber = 0;
    int numThreads = 1;

    TableContext tableContext1 = createTableContext(schema1, table1Name, offsetCol, partitionSize,
            maxActivePartitions, false);
    TableContext tableContext2 = createTableContext(schema1, table2Name, offsetCol, partitionSize,
            maxActivePartitions, false);
    TableContext tableContext3 = createTableContext(schema2, table3Name, offsetCol, partitionSize,
            maxActivePartitions, false);

    Map<String, TableContext> tableContextMap = new HashMap<>();

    tableContextMap.put(tableContext1.getQualifiedName(), tableContext1);
    tableContextMap.put(tableContext2.getQualifiedName(), tableContext2);
    tableContextMap.put(tableContext3.getQualifiedName(), tableContext3);
    Queue<String> sortedTableOrder = new LinkedList<>();

    sortedTableOrder.add(tableContext1.getQualifiedName());
    sortedTableOrder.add(tableContext2.getQualifiedName());
    sortedTableOrder.add(tableContext3.getQualifiedName());

    Map threadNumToMaxTableSlots = new HashMap<>();

    BatchTableStrategy batchTableStrategy = BatchTableStrategy.PROCESS_ALL_AVAILABLE_ROWS_FROM_TABLE;
    MultithreadedTableProvider provider = new MultithreadedTableProvider(tableContextMap, sortedTableOrder,
            threadNumToMaxTableSlots, numThreads, batchTableStrategy);

    assertThat(provider.getRemainingSchemasToTableContexts().size(), equalTo(3));

    TableRuntimeContext table1 = provider.nextTable(threadNumber);
    Assert.equals(table1Name, table1.getSourceTableContext().getTableName());

    assertThat(provider.getRemainingSchemasToTableContexts().size(), equalTo(3));
    // there should be two tables remaining in schema1 (table1 and table2)
    assertThat(provider.getRemainingSchemasToTableContexts().get(schema1).size(), equalTo(2));
    // and one remaining in schema2 (table3)
    assertThat(provider.getRemainingSchemasToTableContexts().get(schema2).size(), equalTo(1));

    final AtomicBoolean tableFinished = new AtomicBoolean(false);
    final AtomicBoolean schemaFinished = new AtomicBoolean(false);
    final List<String> schemaFinishedTables = new LinkedList<>();

    // finish table1
    provider.reportDataOrNoMoreData(table1, 10, 10, true, tableFinished, schemaFinished, schemaFinishedTables);

    // table should be finished
    assertTrue(tableFinished.get());

    // schema should not
    assertFalse(schemaFinished.get());
    assertThat(schemaFinishedTables, empty());
    assertThat(provider.getTablesWithNoMoreData().size(), equalTo(1));

    // there should be a total of two remaining entries in the map
    assertThat(provider.getRemainingSchemasToTableContexts().size(), equalTo(2));
    // one of which is in schema1
    assertThat(provider.getRemainingSchemasToTableContexts().get(schema1).size(), equalTo(1));
    // and one of which is in schema2
    assertThat(provider.getRemainingSchemasToTableContexts().get(schema2).size(), equalTo(1));

    provider.releaseOwnedTable(table1, 1);
    tableFinished.set(false);
    schemaFinished.set(false);
    schemaFinishedTables.clear();

    TableRuntimeContext table2 = provider.nextTable(threadNumber);
    Assert.equals(table2Name, table2.getSourceTableContext().getTableName());

    // finish table2
    provider.reportDataOrNoMoreData(table2, 10, 10, true, tableFinished, schemaFinished, schemaFinishedTables);

    // table should be finished
    assertTrue(tableFinished.get());
    // as should the schema this time
    assertTrue(schemaFinished.get());
    assertThat(schemaFinishedTables, hasSize(2));
    assertThat(provider.getTablesWithNoMoreData().size(), equalTo(2));
    // there should only be one entry left now
    assertThat(provider.getRemainingSchemasToTableContexts().size(), equalTo(1));
    assertTrue(provider.getRemainingSchemasToTableContexts().get(schema1).isEmpty());
    // which is for schema2
    assertThat(provider.getRemainingSchemasToTableContexts().get(schema2).size(), equalTo(1));

    provider.releaseOwnedTable(table2, 1);
    tableFinished.set(false);
    schemaFinished.set(false);
    schemaFinishedTables.clear();

    TableRuntimeContext table3 = provider.nextTable(threadNumber);
    Assert.equals(table3Name, table3.getSourceTableContext().getTableName());

    // suppose we did NOT actually reach the end of table3, in which case the conditions should be the same as above
    provider.reportDataOrNoMoreData(table3, 10, 10, false, tableFinished, schemaFinished, schemaFinishedTables);

    // now neither the table
    assertFalse(tableFinished.get());
    // nor schema should be finished
    assertFalse(schemaFinished.get());
    assertThat(schemaFinishedTables, empty());
    // and entries in the map should be the same as above
    assertThat(provider.getTablesWithNoMoreData().size(), equalTo(2));
    assertThat(provider.getRemainingSchemasToTableContexts().size(), equalTo(1));
    assertTrue(provider.getRemainingSchemasToTableContexts().get(schema1).isEmpty());

    provider.releaseOwnedTable(table3, 1);
    tableFinished.set(false);
    schemaFinished.set(false);
    schemaFinishedTables.clear();

    // cycle through table1 and table2 again
    table1 = provider.nextTable(threadNumber);
    provider.releaseOwnedTable(table1, 1);
    table2 = provider.nextTable(threadNumber);
    provider.releaseOwnedTable(table2, 1);

    // and get back to table3
    table3 = provider.nextTable(threadNumber);
    Assert.equals(table3Name, table3.getSourceTableContext().getTableName());

    // now suppose we have finally finished table3
    provider.reportDataOrNoMoreData(table3, 3, 10, true, tableFinished, schemaFinished, schemaFinishedTables);

    // both table
    assertTrue(tableFinished.get());
    // and schema should be finished
    assertTrue(schemaFinished.get());
    assertThat(schemaFinishedTables, hasSize(1));
    assertThat(provider.getTablesWithNoMoreData().size(), equalTo(3));
    // there should now be no more entries in this map
    assertTrue(provider.getRemainingSchemasToTableContexts().isEmpty());

    provider.releaseOwnedTable(table3, 1);

    assertTrue(provider.shouldGenerateNoMoreDataEvent());

}

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/* w ww  .j  a  v  a 2s.com*/
        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.arpnetworking.metrics.impl.ApacheHttpSinkTest.java

@Test
public void testSafeSleep() throws InterruptedException {
    final AtomicBoolean value = new AtomicBoolean(false);
    final Thread thread = new Thread(() -> {
        // Value will not be set if safe sleep throws or is not interrupted.
        ApacheHttpSink.safeSleep(500);//  w w  w.j  a  v a 2  s  . c  om
        value.set(true);
    });

    thread.start();
    Thread.sleep(100);
    thread.interrupt();
    thread.join(600);

    Assert.assertFalse(thread.isAlive());
    Assert.assertTrue(value.get());
}

From source file:br.com.ingenieux.mojo.jbake.WatchMojo.java

public void executeInternal() throws MojoExecutionException {
    reRender();/*w w  w  . j  ava2  s . c om*/

    Long lastProcessed = Long.valueOf(System.currentTimeMillis());

    getLog().info("Now listening for changes on path " + inputDirectory.getPath());

    initServer();

    DirWatcher dirWatcher = null;

    try {
        dirWatcher = new DirWatcher(inputDirectory);
        final AtomicBoolean done = new AtomicBoolean(false);
        final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        (new Thread() {
            @Override
            public void run() {
                try {
                    getLog().info("Running. Enter a blank line to finish. Anything else forces re-rendering.");

                    while (true) {
                        String line = reader.readLine();

                        if (isBlank(line)) {
                            break;
                        }

                        reRender();
                    }
                } catch (Exception exc) {
                    getLog().info("Ooops", exc);
                } finally {
                    done.set(true);
                }
            }
        }).start();

        dirWatcher.start();

        do {
            Long result = dirWatcher.processEvents();

            if (null == result) {
                // do nothing on purpose
            } else if (result >= lastProcessed) {
                getLog().info("Refreshing");

                super.reRender();

                lastProcessed = Long.valueOf(System.currentTimeMillis());
            }
        } while (!done.get());
    } catch (Exception exc) {
        getLog().info("Oops", exc);

        throw new MojoExecutionException("Oops", exc);
    } finally {
        getLog().info("Finishing");

        if (null != dirWatcher)
            dirWatcher.stop();

        stopServer();
    }
}

From source file:org.apache.hadoop.hbase.wal.TestWALSplit.java

@Test(timeout = 300000)
public void testIOEOnOutputThread() throws Exception {
    conf.setBoolean(HBASE_SKIP_ERRORS, false);

    generateWALs(-1);/*from  w w  w  . j a  va2s.com*/
    useDifferentDFSClient();
    FileStatus[] logfiles = fs.listStatus(WALDIR);
    assertTrue("There should be some log file", logfiles != null && logfiles.length > 0);
    // wals with no entries (like the one we don't use in the factory)
    // won't cause a failure since nothing will ever be written.
    // pick the largest one since it's most likely to have entries.
    int largestLogFile = 0;
    long largestSize = 0;
    for (int i = 0; i < logfiles.length; i++) {
        if (logfiles[i].getLen() > largestSize) {
            largestLogFile = i;
            largestSize = logfiles[i].getLen();
        }
    }
    assertTrue("There should be some log greater than size 0.", 0 < largestSize);
    // Set up a splitter that will throw an IOE on the output side
    WALSplitter logSplitter = new WALSplitter(wals, conf, HBASEDIR, fs, null, null, this.mode) {
        @Override
        protected Writer createWriter(Path logfile) throws IOException {
            Writer mockWriter = Mockito.mock(Writer.class);
            Mockito.doThrow(new IOException("Injected")).when(mockWriter).append(Mockito.<Entry>any());
            return mockWriter;
        }
    };
    // Set up a background thread dumper.  Needs a thread to depend on and then we need to run
    // the thread dumping in a background thread so it does not hold up the test.
    final AtomicBoolean stop = new AtomicBoolean(false);
    final Thread someOldThread = new Thread("Some-old-thread") {
        @Override
        public void run() {
            while (!stop.get())
                Threads.sleep(10);
        }
    };
    someOldThread.setDaemon(true);
    someOldThread.start();
    final Thread t = new Thread("Background-thread-dumper") {
        public void run() {
            try {
                Threads.threadDumpingIsAlive(someOldThread);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    t.setDaemon(true);
    t.start();
    try {
        logSplitter.splitLogFile(logfiles[largestLogFile], null);
        fail("Didn't throw!");
    } catch (IOException ioe) {
        assertTrue(ioe.toString().contains("Injected"));
    } finally {
        // Setting this to true will turn off the background thread dumper.
        stop.set(true);
    }
}

From source file:org.apache.bookkeeper.bookie.CreateNewLogTest.java

@Test
public void testCreateNewLogAndCompactionLog() throws Exception {
    ServerConfiguration conf = TestBKConfiguration.newServerConfiguration();

    // Creating a new configuration with a number of
    // ledger directories.
    conf.setLedgerDirNames(ledgerDirs);// w w w.ja va  2s . co  m
    conf.setEntryLogFilePreAllocationEnabled(true);
    LedgerDirsManager ledgerDirsManager = new LedgerDirsManager(conf, conf.getLedgerDirs(),
            new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold()));
    EntryLogger el = new EntryLogger(conf, ledgerDirsManager);
    // set same thread executor for entryLoggerAllocator's allocatorExecutor
    setSameThreadExecutorForEntryLoggerAllocator(el.getEntryLoggerAllocator());
    AtomicBoolean receivedException = new AtomicBoolean(false);

    IntStream.range(0, 2).parallel().forEach((i) -> {
        try {
            if (i % 2 == 0) {
                ((EntryLogManagerBase) el.getEntryLogManager()).createNewLog((long) i);
            } else {
                el.createNewCompactionLog();
            }
        } catch (IOException e) {
            LOG.error("Received exception while creating newLog", e);
            receivedException.set(true);
        }
    });

    Assert.assertFalse("There shouldn't be any exceptions while creating newlog", receivedException.get());
    Assert.assertEquals("previousAllocatedEntryLogId after 2 times createNewLog is called", 2,
            el.getPreviousAllocatedEntryLogId());
}

From source file:com.netflix.conductor.core.events.TestEventProcessor.java

@Test
public void testEventProcessor() throws Exception {
    String event = "sqs:arn:account090:sqstest1";
    String queueURI = "arn:account090:sqstest1";

    EventQueueProvider provider = mock(EventQueueProvider.class);

    ObservableQueue queue = mock(ObservableQueue.class);
    Message[] messages = new Message[1];
    messages[0] = new Message("t0", "{}", "t0");
    Observable<Message> msgObservable = Observable.from(messages);
    when(queue.observe()).thenReturn(msgObservable);
    when(queue.getURI()).thenReturn(queueURI);
    when(queue.getName()).thenReturn(queueURI);
    when(queue.getType()).thenReturn("sqs");
    when(provider.getQueue(queueURI)).thenReturn(queue);

    EventQueues.registerProvider(QueueType.sqs, provider);

    EventHandler eh = new EventHandler();
    eh.setName(UUID.randomUUID().toString());
    eh.setActive(false);/*from  w  ww . ja va  2s  .co m*/
    Action action = new Action();
    action.setAction(Type.start_workflow);
    action.setStart_workflow(new StartWorkflow());
    action.getStart_workflow().setName("workflow_x");
    action.getStart_workflow().setVersion(1); //TODO: Remove this to simulate the null value for version being passed!
    eh.getActions().add(action);
    eh.setEvent(event);

    MetadataService ms = mock(MetadataService.class);

    when(ms.getEventHandlers()).thenReturn(Arrays.asList(eh));
    when(ms.getEventHandlersForEvent(eh.getEvent(), true)).thenReturn(Arrays.asList(eh));

    //Execution Service Mock
    ExecutionService eservice = mock(ExecutionService.class);
    when(eservice.addEventExecution(any())).thenReturn(true);

    //Workflow Executor Mock
    WorkflowExecutor executor = mock(WorkflowExecutor.class);
    String id = UUID.randomUUID().toString();
    AtomicBoolean started = new AtomicBoolean(false);
    doAnswer(new Answer<String>() {

        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            started.set(true);
            return id;
        }
    }).when(executor).startWorkflow(action.getStart_workflow().getName(), 1,
            action.getStart_workflow().getCorrelationId(), action.getStart_workflow().getInput());

    //Metadata Service Mock
    MetadataService metadata = mock(MetadataService.class);
    WorkflowDef def = new WorkflowDef();
    def.setVersion(1);
    def.setName(action.getStart_workflow().getName());
    when(metadata.getWorkflowDef(any(), any())).thenReturn(def);

    ActionProcessor ap = new ActionProcessor(executor, metadata);

    EventProcessor ep = new EventProcessor(eservice, ms, ap, new TestConfiguration(), new ObjectMapper());
    assertNotNull(ep.getQueues());
    assertEquals(1, ep.getQueues().size());

    String queueEvent = ep.getQueues().keySet().iterator().next();
    assertEquals(eh.getEvent(), queueEvent);

    String epQueue = ep.getQueues().values().iterator().next();
    assertEquals(queueURI, epQueue);

    Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
    assertTrue(started.get());
}

From source file:com.bt.aloha.media.testing.mockphones.ConvediaMockphoneBean.java

private void processMsmlCancelMediaRequest(final String dialogId, final String commandId) {
    final AtomicBoolean needToSendDtmfTerminatedResponse = new AtomicBoolean(false);
    final DialogInfo dialogInfo = getDialogCollection().get(dialogId);
    String originalAudioFileUri = dialogInfo.getApplicationData();
    String responseContent = null;
    if (originalAudioFileUri.indexOf(PLAY_TERMINATED_STRING_PROPERTY_KEY) > -1) {
        responseContent = new MsmlAnnouncementResponse(commandId, ONE_HUNDRED_MS, PLAY_TERMINATED).getXml();
    } else if (originalAudioFileUri.indexOf(DTMF_PLAY_TERMINATED_STRING_PROPERTY_KEY) > -1) {
        responseContent = new MsmlPromptAndCollectDigitsAnnouncementResponse(commandId, ONE_HUNDRED_MS,
                PLAY_TERMINATED).getXml();
    } else if (originalAudioFileUri.indexOf(DTMF_TERMINATED_STRING_PROPERTY_KEY) > -1) {
        responseContent = new MsmlPromptAndCollectDigitsAnnouncementResponse(commandId, ONE_HUNDRED_MS,
                "play.complete").getXml();
        needToSendDtmfTerminatedResponse.set(true);
    }/*  w w w.  j  a  va  2s.  com*/
    sendMediaResponse(dialogId, commandId, responseContent);

    if (needToSendDtmfTerminatedResponse.get()) {
        responseContent = new MsmlPromptAndCollectDigitsCollectedResponse(commandId, ONE_HUNDRED_MS,
                "dtmf.terminated").getXml();
        sendMediaResponse(dialogId, commandId, responseContent);
    }
}

From source file:com.google.dart.java2dart.Context.java

private void dontUseThisInFieldInitializers(CompilationUnit unit) {
    unit.accept(new RecursiveASTVisitor<Void>() {
        @Override//from w ww  .  j  a  v a2  s .c o  m
        public Void visitClassDeclaration(ClassDeclaration node) {
            processClass(node);
            return super.visitClassDeclaration(node);
        }

        private void addAssignmentsToBlock(Block block, Map<SimpleIdentifier, Expression> initializers) {
            int index = 0;
            for (Entry<SimpleIdentifier, Expression> entry : initializers.entrySet()) {
                block.getStatements().add(index++, expressionStatement(assignmentExpression(
                        propertyAccess(thisExpression(), entry.getKey()), TokenType.EQ, entry.getValue())));
            }
        }

        private void processClass(final ClassDeclaration classDeclaration) {
            final Map<SimpleIdentifier, Expression> thisInitializers = Maps.newLinkedHashMap();
            // find field initializers which use "this"
            classDeclaration.accept(new RecursiveASTVisitor<Void>() {
                @Override
                public Void visitVariableDeclaration(VariableDeclaration node) {
                    if (node.getParent().getParent() instanceof FieldDeclaration) {
                        if (hasThisExpression(node)) {
                            thisInitializers.put(node.getName(), node.getInitializer());
                            node.setInitializer(null);
                        }
                    }
                    return super.visitVariableDeclaration(node);
                }

                private boolean hasThisExpression(ASTNode node) {
                    final AtomicBoolean result = new AtomicBoolean();
                    node.accept(new GeneralizingASTVisitor<Void>() {
                        @Override
                        public Void visitThisExpression(ThisExpression node) {
                            result.set(true);
                            return super.visitThisExpression(node);
                        }
                    });
                    return result.get();
                }
            });
            // add field assignment for each "this" field initializer
            if (thisInitializers.isEmpty()) {
                return;
            }
            ConstructorDeclaration singleConstructor = null;
            boolean hasImpl = false;
            for (ClassMember classMember : classDeclaration.getMembers()) {
                if (classMember instanceof ConstructorDeclaration) {
                    singleConstructor = (ConstructorDeclaration) classMember;
                }
                if (classMember instanceof MethodDeclaration) {
                    MethodDeclaration method = (MethodDeclaration) classMember;
                    String methodName = method.getName().getName();
                    if (methodName.startsWith("_jtd_constructor_") && methodName.endsWith("_impl")) {
                        hasImpl = true;
                        Block block = ((BlockFunctionBody) method.getBody()).getBlock();
                        addAssignmentsToBlock(block, thisInitializers);
                    }
                }
            }
            // no "_impl", add assignments to the single constructor
            if (!hasImpl && singleConstructor != null) {
                Block block = ((BlockFunctionBody) singleConstructor.getBody()).getBlock();
                addAssignmentsToBlock(block, thisInitializers);
            }
            // no "_impl", generate default constructor
            if (singleConstructor == null) {
                Block block = block();
                addAssignmentsToBlock(block, thisInitializers);
                ConstructorDeclaration constructor = constructorDeclaration(classDeclaration.getName(), null,
                        formalParameterList(), null, blockFunctionBody(block));
                classDeclaration.getMembers().add(constructor);
            }
        }
    });
}

From source file:io.nats.client.ITClusterTest.java

@Test
public void testProperFalloutAfterMaxAttempts() throws Exception {
    Options opts = new Options.Builder(defaultOptions()).dontRandomize().maxReconnect(5)
            .reconnectWait(25, TimeUnit.MILLISECONDS).build();
    opts.servers = Nats.processUrlArray(testServers);

    final CountDownLatch dcLatch = new CountDownLatch(1);
    opts.disconnectedCb = new DisconnectedCallback() {
        public void onDisconnect(ConnectionEvent event) {
            dcLatch.countDown();//from   w  w  w.j  av  a  2 s.c o  m
        }
    };

    final AtomicBoolean closedCbCalled = new AtomicBoolean(false);
    final CountDownLatch ccLatch = new CountDownLatch(1);
    opts.closedCb = new ClosedCallback() {
        public void onClose(ConnectionEvent event) {
            closedCbCalled.set(true);
            ccLatch.countDown();
        }
    };

    try (NatsServer s1 = runServerOnPort(1222)) {
        try (Connection c = opts.connect()) {
            s1.shutdown();

            // wait for disconnect
            assertTrue("Did not receive a disconnect callback message", await(dcLatch, 2, TimeUnit.SECONDS));

            // Wait for ClosedCB
            assertTrue("Did not receive a closed callback message", await(ccLatch, 2, TimeUnit.SECONDS));

            // Make sure we are not still reconnecting.
            assertTrue("Closed CB was not triggered, should have been.", closedCbCalled.get());

            // Expect connection to be closed...
            assertTrue("Wrong status: " + c.getState(), c.isClosed());
        }
    }
}