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 Hadoop job w/ {@code asakusa-resources.xml}.
 *///from w w  w .  jav  a  2s . com
@Test
public void executeJob_w_resources() {
    prepareJobflow();
    AtomicBoolean call = new AtomicBoolean();
    MockHadoopJob.callback((args, conf) -> {
        call.set(true);
        assertThat(conf.get("com.example.testing"), is("true"));
        return 0;
    });

    JobExecutor executor = new InProcessJobExecutor(context);
    deploy("dummy.xml", new File(framework.getHome(), InProcessJobExecutor.PATH_ASAKUSA_RESOURCES));
    try {
        executor.execute(job(MockHadoopJob.class.getName()), 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 w/ properties.
 *///from   www  .j  a va2s .  c  om
@Test
public void executeJob_w_properties() {
    prepareJobflow();
    AtomicBoolean call = new AtomicBoolean();
    MockHadoopJob.callback((args, conf) -> {
        call.set(true);
        assertThat(conf.get("com.example.testing"), is("true"));
        return 0;
    });

    TestExecutionPlan.Job job = job(MockHadoopJob.class.getName(), "com.example.testing", "true");

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

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

private Map<Segment, Long> acquireSegment(long timeLag) throws ReinitializationRequiredException {
    AtomicReference<Map<Segment, Long>> result = new AtomicReference<>();
    AtomicBoolean reinitRequired = new AtomicBoolean(false);
    sync.updateState(state -> {//from   ww  w.  jav a  2s.  c  o m
        if (!state.isReaderOnline(readerId)) {
            reinitRequired.set(true);
            return null;
        }
        int toAcquire = calculateNumSegmentsToAcquire(state);
        if (toAcquire == 0) {
            result.set(Collections.emptyMap());
            return null;
        }
        Map<Segment, Long> unassignedSegments = state.getUnassignedSegments();
        Map<Segment, Long> acquired = new HashMap<>(toAcquire);
        List<ReaderGroupStateUpdate> updates = new ArrayList<>(toAcquire);
        Iterator<Entry<Segment, Long>> iter = unassignedSegments.entrySet().iterator();
        for (int i = 0; i < toAcquire; i++) {
            assert iter.hasNext();
            Entry<Segment, Long> segment = iter.next();
            acquired.put(segment.getKey(), segment.getValue());
            updates.add(new AcquireSegment(readerId, segment.getKey()));
        }
        updates.add(new UpdateDistanceToTail(readerId, timeLag));
        result.set(acquired);
        return updates;
    });
    if (reinitRequired.get()) {
        throw new ReinitializationRequiredException();
    }
    acquireTimer.reset(calculateAcquireTime(sync.getState()));
    return result.get();
}

From source file:io.vertx.camel.OutboundEndpointTest.java

@Test
public void testWithRoute() throws Exception {
    AtomicBoolean calledSpy = new AtomicBoolean();
    AtomicBoolean startedSpy = new AtomicBoolean();
    vertx.createHttpServer().requestHandler(request -> {
        calledSpy.set(true);
        request.response().end("Alright");
    }).listen(8081, ar -> {//from   ww w. ja va2 s  .co  m
        startedSpy.set(ar.succeeded());
    });

    await().atMost(DEFAULT_TIMEOUT).untilAtomic(startedSpy, is(true));

    camel.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:my-route").to("seda:next").to("http://localhost:8081");
        }
    });

    bridge = CamelBridge.create(vertx, new CamelBridgeOptions(camel)
            .addOutboundMapping(fromVertx("camel-route").toCamel("direct:my-route")));

    camel.start();
    BridgeHelper.startBlocking(bridge);

    vertx.eventBus().send("camel-route", "hello");

    await().atMost(DEFAULT_TIMEOUT).untilAtomic(calledSpy, is(true));
}

From source file:org.alfresco.repo.search.impl.solr.SolrBackupClient.java

public void execute() {
    if (solrQueryHTTPClient.isSharded()) {
        return;//from  w  ww .  java 2s.c  o  m
    }

    String lockToken = getLock(60000);
    if (lockToken == null) {
        return;
    }
    // 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 {
        executeImpl(running);
    } catch (RuntimeException e) {
        throw e;
    } finally {
        // The lock will self-release if answer isActive in the negative
        running.set(false);
        jobLockService.releaseLock(lockToken, lock);
    }
}

From source file:org.apache.hadoop.hbase.regionserver.TestRSKilledWhenInitializing.java

/**
 * Start Master. Get as far as the state where Master is waiting on
 * RegionServers to check in, then return.
 *//*from ww  w. jav  a2 s  .c o m*/
private MasterThread startMaster(MasterThread master) {
    master.start();
    // It takes a while until ServerManager creation to happen inside Master startup.
    while (master.getMaster().getServerManager() == null) {
        continue;
    }
    // Set a listener for the waiting-on-RegionServers state. We want to wait
    // until this condition before we leave this method and start regionservers.
    final AtomicBoolean waiting = new AtomicBoolean(false);
    if (master.getMaster().getServerManager() == null)
        throw new NullPointerException("SM");
    master.getMaster().getServerManager().registerListener(new ServerListener() {
        @Override
        public void waiting() {
            waiting.set(true);
        }
    });
    // Wait until the Master gets to place where it is waiting on RegionServers to check in.
    while (!waiting.get()) {
        continue;
    }
    // Set the global master-is-active; gets picked up by regionservers later.
    masterActive.set(true);
    return master;
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.recovery.TestZKRMStateStoreZKClientConnections.java

@Test(timeout = 20000)
public void testZKClientRetry() throws Exception {
    TestZKClient zkClientTester = new TestZKClient();
    final String path = "/test";
    YarnConfiguration conf = new YarnConfiguration();
    conf.setInt(YarnConfiguration.RM_ZK_TIMEOUT_MS, ZK_TIMEOUT_MS);
    conf.setLong(YarnConfiguration.RM_ZK_RETRY_INTERVAL_MS, 100);
    final ZKRMStateStore store = (ZKRMStateStore) zkClientTester.getRMStateStore(conf);
    TestDispatcher dispatcher = new TestDispatcher();
    store.setRMDispatcher(dispatcher);//from  w w w . j  a va2 s . c o  m
    final AtomicBoolean assertionFailedInThread = new AtomicBoolean(false);

    testingServer.stop();
    Thread clientThread = new Thread() {
        @Override
        public void run() {
            try {
                store.getData(path);
            } catch (Exception e) {
                e.printStackTrace();
                assertionFailedInThread.set(true);
            }
        }
    };
    Thread.sleep(2000);
    testingServer.start();
    clientThread.join();
    Assert.assertFalse(assertionFailedInThread.get());
}

From source file:com.spectralogic.ds3client.helpers.FileObjectPutter_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 {/*from w ww .j  a  v a  2  s  . c om*/
        Files.createFile(Paths.get(tempDirectory.toString(), A_FILE_NAME));
        new FileObjectPutter(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:de.tbuchloh.kiskis.cracker.PasswordCracker.java

public String crackPassword() {
    final Long totalEstimation = _passwordCreator.estimateTotalCount();
    _progressListener.notifyTotalCount(totalEstimation);
    _progressListener.notifyStartTime(System.currentTimeMillis());

    final AtomicBoolean found = new AtomicBoolean(false);
    final Callable<String> callable = new Callable<String>() {

        @Override//from   w  w  w .j a  v  a2 s.c  o  m
        public String call() throws Exception {
            String guess;
            while (!found.get() && (guess = _passwordCreator.create()) != null) {
                _progressListener.notifyTry(guess);
                if (_tester.test(guess)) {
                    found.set(true);
                    return guess;
                }
            }
            return null;
        }
    };

    final int cpus = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
    LOG.info(String.format("Found %1$d cpus ...", cpus));
    final ExecutorService threadPool = Executors.newFixedThreadPool(cpus);
    final Collection<Callable<String>> tasks = new ArrayList<Callable<String>>();
    for (int i = 0; i < cpus; ++i) {
        tasks.add(callable);
    }
    try {
        final List<Future<String>> futures = threadPool.invokeAll(tasks);
        for (final Future<String> future : futures) {
            final String guessedPwd = future.get();
            if (guessedPwd != null) {
                return guessedPwd;
            }
        }
        return null;
    } catch (final InterruptedException e) {
        throw new KisKisRuntimeException("InterruptedException", e);
    } catch (final ExecutionException e) {
        throw new KisKisRuntimeException("ExecutionException", e);
    }
}

From source file:org.pentaho.di.trans.steps.httppost.HTTPPOSTIT.java

private HttpHandler getEncodingCheckingHandler(String expectedResultString, String expectedEncoding,
        AtomicBoolean testStatus) {
    return httpExchange -> {
        try {/*from w  ww  .  ja  va 2s  . c om*/
            checkEncoding(expectedResultString, expectedEncoding, httpExchange.getRequestBody());
            testStatus.set(true);
        } catch (Throwable e) {
            e.printStackTrace();
            testStatus.set(false);
        } finally {
            httpExchange.sendResponseHeaders(200, 0);
            httpExchange.close();
        }
    };
}