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:com.adaptris.core.lms.StreamWrapperCase.java

@Test
public void testOutputStream_Write() throws Exception {
    StreamWrapper wrapper = createWrapper(false);
    File file = TempFileUtils.createTrackedFile(wrapper);
    AtomicBoolean callback = new AtomicBoolean(false);
    OutputStream out = wrapper.openOutputStream(file, () -> {
        callback.set(true);/*from   w ww .  j  a  v a2  s  .com*/
    });
    try (OutputStream closeable = out) {
        out.write(BYTES_TEXT[0]);
    }
    tryQuietly(() -> {
        out.close();
    });
    assertTrue(callback.get());
}

From source file:de.hybris.platform.jdbcwrapper.ConnectionPoolTest.java

private void doTestMultithreadedAccess(final int RUN_SECONDS, final int THREADS, final int PERCENT_NO_TX,
        final int PERCENT_TX_ROLLBACK, final boolean useInterrupt, final boolean sendDummyStatement) {
    HybrisDataSource dataSource = null;/*from w  w w.j a v  a2 s. c o  m*/

    LOG.info("--- test multithreaded access to connection pool duration:" + RUN_SECONDS + "s threads:" + THREADS
            + " nonTx:" + PERCENT_NO_TX + "% rollback:" + PERCENT_TX_ROLLBACK + "% interrupt:" + useInterrupt
            + "-----------------------------------");
    try {
        final Collection<TestConnectionImpl> allConnections = new ConcurrentLinkedQueue<TestConnectionImpl>();

        final AtomicLong rollbackCounter = new AtomicLong(0);
        final AtomicLong connectionCounter = new AtomicLong(0);
        final AtomicBoolean finished = new AtomicBoolean(false);

        dataSource = createDataSource(Registry.getCurrentTenantNoFallback(), allConnections, connectionCounter,
                false, false);

        assertEquals(0, dataSource.getNumInUse());
        assertEquals(1, dataSource.getNumPhysicalOpen());
        assertEquals(1, dataSource.getMaxInUse());
        assertEquals(1, dataSource.getMaxPhysicalOpen());

        final int maxConnections = dataSource.getMaxAllowedPhysicalOpen();

        final String runId = "[" + RUN_SECONDS + "|" + THREADS + "|" + PERCENT_NO_TX + "|" + PERCENT_TX_ROLLBACK
                + "|" + useInterrupt + "]";

        final Runnable runnable = new ContinuousAccessRunnable(dataSource, PERCENT_NO_TX, PERCENT_TX_ROLLBACK,
                rollbackCounter, finished, runId, sendDummyStatement);

        final TestThreadsHolder threadsHolder = new TestThreadsHolder(THREADS, runnable) {
            @Override
            public void stopAll() {
                if (useInterrupt) {
                    super.stopAll();
                } else {
                    finished.set(true);
                }
            }
        };

        threadsHolder.startAll();

        waitDuration(RUN_SECONDS, maxConnections, dataSource, allConnections);

        threadsHolder.stopAll();
        final boolean allStoppedNormal = threadsHolder.waitForAll(30, TimeUnit.SECONDS);

        if (!allStoppedNormal) {
            // try fallback method
            finished.set(true);
            final boolean allStoppedFallback = threadsHolder.waitForAll(10, TimeUnit.SECONDS);
            if (allStoppedFallback) {
                LOG.error("Threads did not stop normally but only after using boolean flag!");
            } else {
                fail("db connection test threads did not stop correctly even after fallback method");
            }
        }

        // kill data source
        dataSource.destroy();
        assertTrue(dataSource.getConnectionPool().isPoolClosed());
        assertTrue(waitForAllInactive(dataSource.getConnectionPool(), 10, TimeUnit.SECONDS));

        if (PERCENT_TX_ROLLBACK > 0) {
            assertTrue(rollbackCounter.get() > 0);
        }

        final long maxAllowedConnections = maxConnections + rollbackCounter.get();

        final Stats stats = getStats(allConnections);

        LOG.info(//
                "max connections :" + maxConnections + "\n" + //
                        "rollbacks :" + rollbackCounter.get() + "\n" + //
                        "real connections :" + connectionCounter.get() + "\n" + //
                        "closed:" + stats.closed + "\n" + //
                        "open:" + stats.open + "\n" + //
                        "borrowed :" + stats.borrowed + "\n" + //
                        "returned :" + stats.returned + "\n" + //
                        "invalidated :" + stats.invalidated + "\n");

        // we cannot be sure since not each rollbacked connections *must* be re-created
        assertTrue(
                "handed out more than max connections (got:" + connectionCounter.get() + " > max:"
                        + maxAllowedConnections + ")", //
                connectionCounter.get() <= maxAllowedConnections);
        assertEquals("still got " + stats.borrowed + "borrowed connections", 0, stats.borrowed);
        assertEquals(
                "connection count mismatch - total:" + connectionCounter.get() + " <> "
                        + (stats.returned + stats.invalidated) + " (returned:" + stats.returned
                        + " + invalidated:" + stats.invalidated + ")", //
                connectionCounter.get(), stats.returned + stats.invalidated);

        // make sure all connections have been finally closed

        assertEquals(
                "data source " + dataSource + "still got " + dataSource.getNumInUse() + " connections in use", //
                0, dataSource.getNumInUse());
        assertEquals(
                "data source " + dataSource + "still got " + dataSource.getNumPhysicalOpen()
                        + " physical connections open (despite none are in use)", //
                0, dataSource.getNumPhysicalOpen());
        assertTrue(
                "data source " + dataSource + " had more than max allowed connections (max:" + maxConnections
                        + ", max in use:" + dataSource.getMaxInUse() + ")", //
                maxConnections >= dataSource.getMaxInUse());
        assertTrue(
                "data source " + dataSource + " had more than max allowed physical connections (max:"
                        + maxConnections + ", max physical in use:" + dataSource.getMaxPhysicalOpen() + ")", //
                maxConnections >= dataSource.getMaxPhysicalOpen());
    } finally {
        destroyDataSource(dataSource);
    }

}

From source file:gobblin.runtime.StateStoreBasedWatermarkStorageCli.java

@Override
public void run(String[] args) {
    Options options = new Options();
    options.addOption(HELP);//from ww  w .  j a  v  a2  s  . c  om
    options.addOption(ZK);
    options.addOption(JOB_NAME);
    options.addOption(ROOT_DIR);
    options.addOption(WATCH);

    CommandLine cli;
    try {
        CommandLineParser parser = new DefaultParser();
        cli = parser.parse(options, Arrays.copyOfRange(args, 1, args.length));
    } catch (ParseException pe) {
        System.out.println("Command line parse exception: " + pe.getMessage());
        return;
    }

    if (cli.hasOption(HELP.getOpt())) {
        printUsage(options);
        return;
    }

    TaskState taskState = new TaskState();

    String jobName;
    if (!cli.hasOption(JOB_NAME.getOpt())) {
        log.error("Need Job Name to be specified --", JOB_NAME.getLongOpt());
        throw new RuntimeException("Need Job Name to be specified");
    } else {
        jobName = cli.getOptionValue(JOB_NAME.getOpt());
        log.info("Using job name: {}", jobName);
    }
    taskState.setProp(ConfigurationKeys.JOB_NAME_KEY, jobName);

    String zkAddress = "locahost:2181";
    if (cli.hasOption(ZK.getOpt())) {
        zkAddress = cli.getOptionValue(ZK.getOpt());
    }

    log.info("Using zk address : {}", zkAddress);

    taskState.setProp(StateStoreBasedWatermarkStorage.WATERMARK_STORAGE_TYPE_KEY, "zk");
    taskState.setProp("state.store.zk.connectString", zkAddress);

    if (cli.hasOption(ROOT_DIR.getOpt())) {
        String rootDir = cli.getOptionValue(ROOT_DIR.getOpt());
        taskState.setProp(StateStoreBasedWatermarkStorage.WATERMARK_STORAGE_CONFIG_PREFIX
                + ConfigurationKeys.STATE_STORE_ROOT_DIR_KEY, rootDir);
        log.info("Setting root dir to {}", rootDir);
    } else {
        log.error("Need root directory specified");
        printUsage(options);
        return;
    }

    StateStoreBasedWatermarkStorage stateStoreBasedWatermarkStorage = new StateStoreBasedWatermarkStorage(
            taskState);

    final AtomicBoolean stop = new AtomicBoolean(true);

    if (cli.hasOption(WATCH.getOpt())) {
        stop.set(false);
    }
    try {

        if (!stop.get()) {
            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    stop.set(true);
                }
            });
        }
        do {
            boolean foundWatermark = false;
            try {
                for (CheckpointableWatermarkState wmState : stateStoreBasedWatermarkStorage
                        .getAllCommittedWatermarks()) {
                    foundWatermark = true;
                    System.out.println(wmState.getProperties());
                }
            } catch (IOException ie) {
                Throwables.propagate(ie);
            }

            if (!foundWatermark) {
                System.out.println("No watermarks found.");
            }
            if (!stop.get()) {
                Thread.sleep(1000);
            }
        } while (!stop.get());
    } catch (Exception e) {
        Throwables.propagate(e);
    }
}

From source file:com.nridge.core.app.mgr.AppMgr.java

/**
 * Default constructor./*from  w w  w .  j av  a  2s  .  c  o m*/
 */
public AppMgr() {
    mIsPathsExplicit = false;
    mIsAlive = new AtomicBoolean(true);
    mPropertyMap = new HashMap<String, Object>();
    mInsPathName = System.getProperty("user.dir");
    mCfgPathName = String.format("%s%ccfg", mInsPathName, File.separatorChar);
    mLogPathName = String.format("%s%clog", mInsPathName, File.separatorChar);
    mDSPathName = String.format("%s%cds", mInsPathName, File.separatorChar);
    mRDBMSPathName = String.format("%s%crdb", mInsPathName, File.separatorChar);
    mGraphPathName = String.format("%s%cgdb", mInsPathName, File.separatorChar);
}

From source file:com.thinkbiganalytics.metadata.modeshape.security.action.JcrAllowedActions.java

@Override
public boolean enableOnly(Principal principal, Set<Action> actions) {
    final AtomicBoolean result = new AtomicBoolean(false);

    getAvailableActions().stream().forEach(available -> {
        available.stream().forEach(child -> {
            if (actions.contains(child)) {
                result.set(togglePermission(child, principal, true) || result.get());
            } else {
                togglePermission(child, principal, false);
            }//w ww .j ava 2s  .c om
        });
    });

    return result.get();
}

From source file:com.nridge.connector.fs.con_fs.task.TaskConnectorFS.java

/**
 * Returns <i>true</i> if this task was properly initialized
 * and is currently executing./*from  ww w. j  a va2s  . co  m*/
 *
 * @return <i>true</i> or <i>false</i>
 */
@Override
public boolean isAlive() {
    if (mIsAlive == null)
        mIsAlive = new AtomicBoolean(false);

    return mIsAlive.get();
}

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

/**
 * Add this reader to the reader group so that it is able to acquire segments
 *//*from w  ww . ja  va 2 s .  co m*/
void initializeReader(long initialAllocationDelay) {
    AtomicBoolean alreadyAdded = new AtomicBoolean(false);
    sync.updateState(state -> {
        if (state.getSegments(readerId) == null) {
            return Collections.singletonList(new AddReader(readerId));
        } else {
            alreadyAdded.set(true);
            return null;
        }
    });
    if (alreadyAdded.get()) {
        throw new IllegalStateException("The requested reader: " + readerId
                + " cannot be added to the group because it is already in the group. Perhaps close() was not called?");
    }
    long randomDelay = (long) (RandomUtils.nextFloat()
            * Math.min(initialAllocationDelay, sync.getState().getConfig().getGroupRefreshTimeMillis()));
    acquireTimer.reset(Duration.ofMillis(initialAllocationDelay + randomDelay));
}

From source file:org.geowebcache.storage.blobstore.memory.MemoryBlobStore.java

public MemoryBlobStore() {
    // Initialization of the various elements
    this.executorService = Executors.newFixedThreadPool(1);
    lock = new ReentrantReadWriteLock(true);
    blobStoreStateLock = lock.writeLock();
    componentsStateLock = lock.readLock();
    cacheAlreadySet = new AtomicBoolean(false);
    // Initialization of the cacheProvider and store. Must be overridden, this uses default and caches in memory
    setStore(new NullBlobStore());
    GuavaCacheProvider startingCache = new GuavaCacheProvider(new CacheConfiguration());
    this.cacheProvider = startingCache;
}

From source file:org.lol.reddit.reddit.api.RedditAPIIndividualSubredditDataRequester.java

public void performRequest(final Collection<String> subredditCanonicalIds, final TimestampBound timestampBound,
        final RequestResponseHandler<HashMap<String, RedditSubreddit>, SubredditRequestFailure> handler) {

    // TODO if there's a bulk API to do this, that would be good... :)

    final HashMap<String, RedditSubreddit> result = new HashMap<String, RedditSubreddit>();
    final AtomicBoolean stillOkay = new AtomicBoolean(true);
    final AtomicInteger requestsToGo = new AtomicInteger(subredditCanonicalIds.size());
    final AtomicLong oldestResult = new AtomicLong(Long.MAX_VALUE);

    final RequestResponseHandler<RedditSubreddit, SubredditRequestFailure> innerHandler = new RequestResponseHandler<RedditSubreddit, SubredditRequestFailure>() {
        @Override/*from   w w  w  . j a  v  a2 s.com*/
        public void onRequestFailed(SubredditRequestFailure failureReason) {
            synchronized (result) {
                if (stillOkay.get()) {
                    stillOkay.set(false);
                    handler.onRequestFailed(failureReason);
                }
            }
        }

        @Override
        public void onRequestSuccess(RedditSubreddit innerResult, long timeCached) {
            synchronized (result) {
                if (stillOkay.get()) {

                    result.put(innerResult.getKey(), innerResult);
                    oldestResult.set(Math.min(oldestResult.get(), timeCached));

                    if (requestsToGo.decrementAndGet() == 0) {
                        handler.onRequestSuccess(result, oldestResult.get());
                    }
                }
            }
        }
    };

    for (String subredditCanonicalId : subredditCanonicalIds) {
        performRequest(subredditCanonicalId, timestampBound, innerHandler);
    }
}

From source file:com.qq.tars.service.server.ServerService.java

public ServerConf getServerConf4Tree(String treeNodeId) {
    ServerConf serverConf = new ServerConf();
    AtomicBoolean enableSet = new AtomicBoolean(false);
    Arrays.stream(treeNodeId.split("\\.")).forEach(s -> {
        int i = Integer.parseInt(s.substring(0, 1));
        String v = s.substring(1);
        switch (i) {
        case 1://from  w  ww.  j a v a 2  s. c o m
            serverConf.setApplication(v);
            break;
        case 2:
            serverConf.setSetName(v);
            enableSet.set(true);
            break;
        case 3:
            serverConf.setSetArea(v);
            enableSet.set(true);
            break;
        case 4:
            serverConf.setSetGroup(v);
            enableSet.set(true);
            break;
        case 5:
            serverConf.setServerName(v);
            break;
        default:
            break;
        }
    });
    serverConf.setEnableSet(enableSet.get() ? "Y" : "N");
    return serverConf;
}