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

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

Introduction

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

Prototype

public final void set(boolean newValue) 

Source Link

Document

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

Usage

From source file:eu.stratosphere.pact.runtime.task.ReduceTaskTest.java

@Test
public void testCancelReduceTaskWhileSorting() {
    addInputComparator(this.comparator);
    setOutput(new NirvanaOutputList());
    getTaskConfig().setDriverStrategy(DriverStrategy.SORTED_GROUP_REDUCE);

    final GroupReduceDriver<Record, Record> testTask = new GroupReduceDriver<Record, Record>();

    try {//from w w w  . ja  v a  2s .com
        addInputSorted(new DelayingInfinitiveInputIterator(100), this.comparator.duplicate());
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail();
    }

    final AtomicBoolean success = new AtomicBoolean(false);

    Thread taskRunner = new Thread() {
        @Override
        public void run() {
            try {
                testDriver(testTask, MockReduceStub.class);
                success.set(true);
            } catch (Exception ie) {
                ie.printStackTrace();
            }
        }
    };
    taskRunner.start();

    TaskCancelThread tct = new TaskCancelThread(1, taskRunner, this);
    tct.start();

    try {
        tct.join();
        taskRunner.join();
    } catch (InterruptedException ie) {
        Assert.fail("Joining threads failed");
    }

    Assert.assertTrue("Test threw an exception even though it was properly canceled.", success.get());
}

From source file:eu.stratosphere.pact.runtime.task.ReduceTaskTest.java

@Test
public void testCancelReduceTaskWhileReducing() {

    final int keyCnt = 1000;
    final int valCnt = 2;

    addInput(new UniformRecordGenerator(keyCnt, valCnt, true));
    addInputComparator(this.comparator);
    setOutput(new NirvanaOutputList());
    getTaskConfig().setDriverStrategy(DriverStrategy.SORTED_GROUP_REDUCE);

    final GroupReduceDriver<Record, Record> testTask = new GroupReduceDriver<Record, Record>();

    final AtomicBoolean success = new AtomicBoolean(false);

    Thread taskRunner = new Thread() {
        @Override// w  w  w .  jav a 2  s.  c o m
        public void run() {
            try {
                testDriver(testTask, MockDelayingReduceStub.class);
                success.set(true);
            } catch (Exception ie) {
                ie.printStackTrace();
            }
        }
    };
    taskRunner.start();

    TaskCancelThread tct = new TaskCancelThread(2, taskRunner, this);
    tct.start();

    try {
        tct.join();
        taskRunner.join();
    } catch (InterruptedException ie) {
        Assert.fail("Joining threads failed");
    }

}

From source file:com.yahoo.sql4d.sql4ddriver.sql.MysqlAccessor.java

/**
 * Suitable for CRUD operations where no result set is expected.
 * @param params//from  www  .  j  a v  a  2  s  .  c  om
 * @param query 
 * @return  
 */
public boolean execute(Map<String, String> params, String query) {
    final AtomicBoolean result = new AtomicBoolean(false);
    Tuple2<DataSource, Connection> conn = null;
    try {
        conn = getConnection();
        NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(conn._1());
        jdbcTemplate.execute(query, params, new PreparedStatementCallback<Void>() {
            @Override
            public Void doInPreparedStatement(PreparedStatement ps) {
                try {
                    result.set(ps.execute());
                } catch (SQLException e) {
                    result.set(false);
                }
                return null;
            }
        });
    } catch (Exception ex) {
        Logger.getLogger(MysqlAccessor.class.getName()).log(Level.SEVERE, null, ex);
        result.set(false);
    } finally {
        returnConnection(conn);
    }
    return result.get();
}

From source file:org.apache.jackrabbit.oak.spi.blob.AbstractBlobStoreTest.java

@Test
public void testCloseStream() throws Exception {
    final AtomicBoolean closed = new AtomicBoolean();
    InputStream in = new InputStream() {
        @Override//  w w  w  . jav a 2  s . c  o  m
        public void close() {
            closed.set(true);
        }

        @Override
        public int read() throws IOException {
            return -1;
        }
    };
    store.writeBlob(in);
    assertTrue(closed.get());
}

From source file:org.apache.jackrabbit.oak.spi.blob.AbstractBlobStoreTest.java

@Test
public void testExceptionWhileReading() throws Exception {
    final AtomicBoolean closed = new AtomicBoolean();
    InputStream in = new InputStream() {
        @Override/*  www . j  av a2 s  .com*/
        public void close() {
            closed.set(true);
        }

        @Override
        public int read() throws IOException {
            throw new RuntimeException("abc");
        }
    };
    try {
        store.writeBlob(in);
    } catch (Exception e) {
        String msg = e.getMessage();
        assertTrue(msg, msg.indexOf("abc") >= 0);
    }
    assertTrue(closed.get());
}

From source file:com.netflix.conductor.core.execution.TestWorkflowExecutor.java

@Test
public void test() throws Exception {

    AtomicBoolean httpTaskExecuted = new AtomicBoolean(false);
    AtomicBoolean http2TaskExecuted = new AtomicBoolean(false);

    new Wait();//from ww w. j a  v  a2 s  .c om
    new WorkflowSystemTask("HTTP") {
        @Override
        public boolean isAsync() {
            return true;
        }

        @Override
        public void start(Workflow workflow, Task task, WorkflowExecutor executor) throws Exception {
            httpTaskExecuted.set(true);
            task.setStatus(Status.COMPLETED);
            super.start(workflow, task, executor);
        }

    };

    new WorkflowSystemTask("HTTP2") {

        @Override
        public void start(Workflow workflow, Task task, WorkflowExecutor executor) throws Exception {
            http2TaskExecuted.set(true);
            task.setStatus(Status.COMPLETED);
            super.start(workflow, task, executor);
        }

    };

    Workflow workflow = new Workflow();
    workflow.setWorkflowId("1");

    TestConfiguration config = new TestConfiguration();
    MetadataDAO metadata = mock(MetadataDAO.class);
    ExecutionDAO edao = mock(ExecutionDAO.class);
    QueueDAO queue = mock(QueueDAO.class);
    ObjectMapper om = new ObjectMapper();

    WorkflowExecutor executor = new WorkflowExecutor(metadata, edao, queue, om, config);
    List<Task> tasks = new LinkedList<>();

    WorkflowTask taskToSchedule = new WorkflowTask();
    taskToSchedule.setWorkflowTaskType(Type.USER_DEFINED);
    taskToSchedule.setType("HTTP");

    WorkflowTask taskToSchedule2 = new WorkflowTask();
    taskToSchedule2.setWorkflowTaskType(Type.USER_DEFINED);
    taskToSchedule2.setType("HTTP2");

    WorkflowTask wait = new WorkflowTask();
    wait.setWorkflowTaskType(Type.WAIT);
    wait.setType("WAIT");
    wait.setTaskReferenceName("wait");

    Task task1 = SystemTask.userDefined(workflow, IDGenerator.generate(), taskToSchedule, new HashMap<>(), null,
            0);
    Task task2 = SystemTask.waitTask(workflow, IDGenerator.generate(), taskToSchedule, new HashMap<>());
    Task task3 = SystemTask.userDefined(workflow, IDGenerator.generate(), taskToSchedule2, new HashMap<>(),
            null, 0);

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

    when(edao.createTasks(tasks)).thenReturn(tasks);
    AtomicInteger startedTaskCount = new AtomicInteger(0);
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            startedTaskCount.incrementAndGet();
            return null;
        }
    }).when(edao).updateTask(any());

    AtomicInteger queuedTaskCount = new AtomicInteger(0);
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            String queueName = invocation.getArgumentAt(0, String.class);
            System.out.println(queueName);
            queuedTaskCount.incrementAndGet();
            return null;
        }
    }).when(queue).push(any(), any(), anyInt());

    boolean stateChanged = executor.scheduleTask(workflow, tasks);
    assertEquals(2, startedTaskCount.get());
    assertEquals(1, queuedTaskCount.get());
    assertTrue(stateChanged);
    assertFalse(httpTaskExecuted.get());
    assertTrue(http2TaskExecuted.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//from   w  w  w  . j a v a 2 s. c om
        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:biz.ganttproject.impex.csv.CsvImportTest.java

public void testTwoGroups() throws Exception {
    String header1 = "A, B";
    String data1 = "a1, b1";
    final AtomicBoolean wasCalled1 = new AtomicBoolean(false);
    RecordGroup recordGroup1 = new RecordGroup("AB", ImmutableSet.<String>of("A", "B")) {
        @Override/*from   w  ww. ja v  a2 s  .  c  o m*/
        protected boolean doProcess(CSVRecord record) {
            if (!super.doProcess(record)) {
                return false;
            }
            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);
    RecordGroup recordGroup2 = new RecordGroup("CDE", ImmutableSet.<String>of("C", "D", "E")) {
        @Override
        protected boolean doProcess(CSVRecord record) {
            if (!super.doProcess(record)) {
                return false;
            }
            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.adaptris.core.fs.NonDeletingFsConsumerTest.java

public void testConsumeNotReprocessed() throws Exception {
    String subDir = new GuidGenerator().safeUUID();
    MockMessageListener stub = new MockMessageListener(10);
    NonDeletingFsConsumer fs = createConsumer(subDir, "testConsume");
    AtomicBoolean pollFired = new AtomicBoolean(false);
    fs.setPoller(/*ww w. j  ava 2  s  .  c  o m*/
            new FixedIntervalPoller(new TimeInterval(500L, TimeUnit.MILLISECONDS)).withPollerCallback(e -> {
                if (e == 0) {
                    pollFired.set(true);
                }
            }));
    StandaloneConsumer sc = new StandaloneConsumer(fs);
    sc.registerAdaptrisMessageListener(stub);
    int count = 10;
    File parentDir = FsHelper
            .createFileReference(FsHelper.createUrlFromString(PROPERTIES.getProperty(BASE_KEY), true));
    try {
        File baseDir = new File(parentDir, subDir);
        LifecycleHelper.init(sc);
        createFiles(baseDir, ".xml", count);
        LifecycleHelper.start(sc);
        waitForMessages(stub, count);
        // The next call back should be on the next poll, when messages == 0;
        waitForPollCallback(pollFired);
        // that we don't reprocess them.
        assertMessages(stub.getMessages(), count,
                baseDir.listFiles((FilenameFilter) new Perl5FilenameFilter(".*\\.xml")));
    } catch (Exception e) {
        log.warn(e.getMessage(), e);
    } finally {
        stop(sc);
        FileUtils.deleteQuietly(new File(parentDir, subDir));
    }
}

From source file:com.liveramp.hank.test.ZkTestCase.java

@Before
public final void setUpZk() throws Exception {

    setupZkServer();//ww  w.  ja v a  2 s . c o  m

    final Object lock = new Object();
    final AtomicBoolean connected = new AtomicBoolean(false);

    zk = new ZooKeeperPlus("127.0.0.1:" + zkClientPort, 1000000, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            switch (event.getType()) {
            case None:
                if (event.getState() == KeeperState.SyncConnected) {
                    connected.set(true);
                    synchronized (lock) {
                        lock.notifyAll();
                    }
                }
            }
            LOG.debug(event.toString());
        }
    });

    synchronized (lock) {
        lock.wait(2000);
    }
    if (!connected.get()) {
        fail("timed out waiting for the zk client connection to come online!");
    }
    LOG.debug("session timeout: " + zk.getSessionTimeout());

    zk.deleteNodeRecursively(zkRoot);
    WaitUntil.orDie(() -> {
        try {
            return zk.exists(zkRoot, false) == null;
        } catch (KeeperException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    });
    createNodeRecursively(zkRoot);
}