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:com.asakusafw.testdriver.inprocess.InProcessJobExecutorTest.java

/**
 * Test method for executing non-emulated command.
 *//*from ww  w. java2 s  .  c  o m*/
@Test
public void executeCommand_delegate() {
    Assume.assumeTrue("not unix-like", SystemUtils.IS_OS_MAC_OSX || SystemUtils.IS_OS_LINUX);

    File touch = new File("/usr/bin/touch");
    Assume.assumeTrue("no 'touch' command", touch.isFile() && touch.canExecute());

    AtomicBoolean call = new AtomicBoolean();
    MockCommandEmulator.callback(args -> call.set(true));
    File target = new File(framework.getWork("working"), "target");
    Assume.assumeFalse(target.exists());

    // exec: touch .../target
    TestExecutionPlan.Command command = command("generic", touch.getPath(), target.getAbsolutePath());
    JobExecutor executor = new InProcessJobExecutor(context);
    try {
        executor.execute(command, Collections.emptyMap());
    } catch (IOException e) {
        throw new AssertionError(e);
    }
    assertThat(target.exists(), is(true));
    assertThat(call.get(), is(false));
}

From source file:com.ebay.cloud.cms.entmgr.entity.impl.EntityFieldTargetMerger.java

private List<?> mergeUpdateReference(List<IEntity> giveValues, List<IEntity> foundValues,
        AtomicBoolean hasChange) {
    Map<String, IEntity> oids = new HashMap<String, IEntity>();
    for (IEntity entity : foundValues) {
        oids.put(entity.getId(), entity);
    }//from  w ww  .  j a v a 2 s.c o m

    for (IEntity obj : giveValues) {
        if (!oids.containsKey(obj.getId())) {
            hasChange.set(true);
            oids.put(obj.getId(), obj);
        }
    }
    return new ArrayList<IEntity>(oids.values());
}

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

/**
 * Handles a segment being completed by calling the controller to gather all successors to the completed segment.
 *///from   ww w.jav  a 2 s  .  co  m
void handleEndOfSegment(Segment segmentCompleted) throws ReinitializationRequiredException {
    val successors = getAndHandleExceptions(controller.getSuccessors(segmentCompleted), RuntimeException::new);
    AtomicBoolean reinitRequired = new AtomicBoolean(false);
    sync.updateState(state -> {
        if (!state.isReaderOnline(readerId)) {
            reinitRequired.set(true);
            return null;
        }
        return Collections.singletonList(
                new SegmentCompleted(readerId, segmentCompleted, successors.getSegmentToPredecessor()));
    });
    if (reinitRequired.get()) {
        throw new ReinitializationRequiredException();
    }
    acquireTimer.zero();
}

From source file:org.apache.nifi.processors.email.smtp.SmtpConsumer.java

@Override
public void data(final InputStream data) throws RejectException, TooMuchDataException, IOException {
    final ProcessSession processSession = sessionFactory.createSession();
    final StopWatch watch = new StopWatch();
    watch.start();/*w w w.  j av  a 2s .  c o m*/
    try {
        FlowFile flowFile = processSession.create();
        final AtomicBoolean limitExceeded = new AtomicBoolean(false);
        flowFile = processSession.write(flowFile, (OutputStream out) -> {
            final LimitingInputStream lis = new LimitingInputStream(data, maxMessageSize);
            IOUtils.copy(lis, out);
            if (lis.hasReachedLimit()) {
                limitExceeded.set(true);
            }
        });
        if (limitExceeded.get()) {
            throw new TooMuchDataException(
                    "Maximum message size limit reached - client must send smaller messages");
        }
        flowFile = processSession.putAllAttributes(flowFile, extractMessageAttributes());
        watch.stop();
        processSession.getProvenanceReporter().receive(flowFile, "smtp://" + host + ":" + port + "/",
                watch.getDuration(TimeUnit.MILLISECONDS));
        processSession.transfer(flowFile, ListenSMTP.REL_SUCCESS);
        processSession.commit();
    } catch (FlowFileAccessException | IllegalStateException | RejectException | IOException ex) {
        log.error("Unable to fully process input due to " + ex.getMessage(), ex);
        throw ex;
    } finally {
        processSession.rollback(); //make sure this happens no matter what - is safe
    }
}

From source file:org.alfresco.reporting.cron.HarvestingJob.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    JobDataMap jobData = context.getJobDetail().getJobDataMap();
    this.jobLockService = (JobLockService) jobData.get("jobLockService");

    logger.debug("jobLockService hashcode=" + jobLockService.hashCode());

    // get a token for a minute
    String lockToken = getLock(getLockKey(), 60000);
    if (lockToken == null) {
        return;//from   w  ww .ja  va 2  s .c  om
    }
    // Use a flag to keep track of the running job
    final AtomicBoolean running = new AtomicBoolean(true);
    jobLockService.refreshLock(lockToken, lock, 30000, new JobLockRefreshCallback() {
        @Override
        public boolean isActive() {
            return running.get();
        }

        @Override
        public void lockReleased() {
            running.set(false);
        }
    });
    try {
        logger.debug("Start executeImpl");
        executeImpl(running, context);
        logger.debug("End executeImpl");
    } catch (RuntimeException e) {
        throw e;
    } finally {
        // The lock will self-release if answer isActive in the negative
        running.set(false);
        jobLockService.releaseLock(lockToken, getLockKey());
        logger.debug("Released the lock");
    }
}

From source file:io.restassured.path.xml.XmlPathObjectDeserializationTest.java

@Test
public void xml_path_supports_custom_deserializer() {
    // Given/*from   w  w w.ja v  a 2  s  .c o m*/
    final AtomicBoolean customDeserializerUsed = new AtomicBoolean(false);

    final XmlPath xmlPath = new XmlPath(COOL_GREETING)
            .using(XmlPathConfig.xmlPathConfig().defaultObjectDeserializer(new XmlPathObjectDeserializer() {
                public <T> T deserialize(ObjectDeserializationContext ctx) {
                    customDeserializerUsed.set(true);
                    final String xml = ctx.getDataToDeserialize().asString();
                    final Greeting greeting = new Greeting();
                    greeting.setFirstName(StringUtils.substringBetween(xml, "<firstName>", "</firstName>"));
                    greeting.setLastName(StringUtils.substringBetween(xml, "<lastName>", "</lastName>"));
                    return (T) greeting;
                }
            }));

    // When
    final Greeting greeting = xmlPath.getObject("", Greeting.class);

    // Then
    assertThat(greeting.getFirstName(), equalTo("John"));
    assertThat(greeting.getLastName(), equalTo("Doe"));
    assertThat(customDeserializerUsed.get(), is(true));
}

From source file:org.apache.hadoop.yarn.client.TestAMRMClientAsync.java

@Test(timeout = 10000)
public void testAMRMClientAsync() throws Exception {
    Configuration conf = new Configuration();
    List<ContainerStatus> completed1 = Arrays.asList(BuilderUtils
            .newContainerStatus(BuilderUtils.newContainerId(0, 0, 0, 0), ContainerState.COMPLETE, "", 0));
    List<Container> allocated1 = Arrays.asList(BuilderUtils.newContainer(null, null, null, null, null, null));
    final AllocateResponse response1 = createAllocateResponse(new ArrayList<ContainerStatus>(), allocated1);
    final AllocateResponse response2 = createAllocateResponse(completed1, new ArrayList<Container>());
    final AllocateResponse emptyResponse = createAllocateResponse(new ArrayList<ContainerStatus>(),
            new ArrayList<Container>());

    TestCallbackHandler callbackHandler = new TestCallbackHandler();
    AMRMClient client = mock(AMRMClient.class);
    final AtomicBoolean secondHeartbeatReceived = new AtomicBoolean(false);
    when(client.allocate(anyFloat())).thenReturn(response1).thenAnswer(new Answer<AllocateResponse>() {
        @Override/*from w  w  w.j  a  v a 2 s  . co  m*/
        public AllocateResponse answer(InvocationOnMock invocation) throws Throwable {
            secondHeartbeatReceived.set(true);
            return response2;
        }
    }).thenReturn(emptyResponse);
    when(client.registerApplicationMaster(anyString(), anyInt(), anyString())).thenReturn(null);

    AMRMClientAsync asyncClient = new AMRMClientAsync(client, 20, callbackHandler);
    asyncClient.init(conf);
    asyncClient.start();
    asyncClient.registerApplicationMaster("localhost", 1234, null);

    // while the CallbackHandler will still only be processing the first response,
    // heartbeater thread should still be sending heartbeats.
    // To test this, wait for the second heartbeat to be received. 
    while (!secondHeartbeatReceived.get()) {
        Thread.sleep(10);
    }

    // allocated containers should come before completed containers
    Assert.assertEquals(null, callbackHandler.takeCompletedContainers());

    // wait for the allocated containers from the first heartbeat's response
    while (callbackHandler.takeAllocatedContainers() == null) {
        Assert.assertEquals(null, callbackHandler.takeCompletedContainers());
        Thread.sleep(10);
    }

    // wait for the completed containers from the second heartbeat's response
    while (callbackHandler.takeCompletedContainers() == null) {
        Thread.sleep(10);
    }

    asyncClient.stop();

    Assert.assertEquals(null, callbackHandler.takeAllocatedContainers());
    Assert.assertEquals(null, callbackHandler.takeCompletedContainers());
}

From source file:com.asakusafw.testdriver.inprocess.InProcessJobExecutorTest.java

/**
 * Test method for executing emulated command.
 *//* w w w .  j  a  v  a  2s. c om*/
@Test
public void executeCommand_simple() {
    AtomicBoolean call = new AtomicBoolean();
    MockCommandEmulator.callback(args -> {
        call.set(true);
        assertThat(args, contains("hello", "world"));
    });
    JobExecutor executor = new InProcessJobExecutor(context);
    try {
        executor.execute(command("mock", "hello", "world"), Collections.emptyMap());
    } catch (IOException e) {
        throw new AssertionError(e);
    }
    assertThat(call.get(), is(true));
}

From source file:com.asakusafw.testdriver.inprocess.InProcessJobExecutorTest.java

/**
 * Test method for executing Hadoop job.
 *//*from   w  w  w .j a  va 2  s.  com*/
@Test
public void executeJob_simple() {
    prepareJobflow();
    AtomicBoolean call = new AtomicBoolean();
    MockHadoopJob.callback((args, conf) -> {
        call.set(true);
        return 0;
    });

    JobExecutor executor = new InProcessJobExecutor(context);
    try {
        executor.execute(job(MockHadoopJob.class.getName()), Collections.emptyMap());
    } catch (IOException e) {
        throw new AssertionError(e);
    }
    assertThat(call.get(), is(true));
}

From source file:org.apache.geode.distributed.LauncherIntegrationTestCase.java

protected InputListener createExpectedListener(final String name, final String expected,
        final AtomicBoolean atomic) {
    return new InputListener() {
        @Override/* w  w w  .  j a  v  a2s  .  co  m*/
        public void notifyInputLine(String line) {
            if (line.contains(expected)) {
                atomic.set(true);
            }
        }

        @Override
        public String toString() {
            return name;
        }
    };
}