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:de.metas.ui.web.notification.UserNotification.java

private UserNotification(final Event event) {
    super();/*from  w  w  w.j a v  a 2  s.c  om*/

    id = event.getId();
    timestamp = System.currentTimeMillis(); // TODO: introduce Event.getTimestamp()
    important = DisplayType.toBoolean(event.getProperty(EVENT_PARAM_Important), false);

    detailPlain = event.getDetailPlain();
    detailADMessage = event.getDetailADMessage();
    detailADMessageParams = ImmutableMap.copyOf(event.getProperties());

    read = new AtomicBoolean(false);

    //
    // Target: window (from document record)
    final ITableRecordReference targetRecord = event.getRecord();
    if (targetRecord != null) {
        targetType = TargetType.Window;
        final RecordZoomWindowFinder recordWindowFinder = RecordZoomWindowFinder.newInstance(targetRecord);
        target_adWindowId = recordWindowFinder.findAD_Window_ID();
        target_tableName = recordWindowFinder.getTableName();
        target_recordId = recordWindowFinder.getRecord_ID();
    }
    //
    // Target: none
    else {
        targetType = TargetType.None;
        target_adWindowId = -1;
        target_tableName = null;
        target_recordId = -1;
    }
}

From source file:com.github.nethad.clustermeister.provisioning.jppf.LocalDriverBuilder.java

@Override
protected ClustermeisterLauncher doBuild() {
    JPPFDriverConfigurationSource.serverPort = serverPort;
    JPPFDriverConfigurationSource.managementPort = managementPort;
    JPPFDriverConfigurationSource.jvmOptions = configuration
            .getString(ConfigurationKeys.JVM_OPTIONS_LOCAL_DRIVER, "");
    Map<String, String> loadBalancingConfigValues = new DriverLoadBalancing(configuration)
            .getLoadBalancingConfigValues();
    if (loadBalancingConfigValues.isEmpty()) {
        //                logger.info("No load balancing settings set.");
    } else {/*from www . j av a2  s  .  com*/
        for (Map.Entry<String, String> entry : loadBalancingConfigValues.entrySet()) {
            //                    logger.info("{} => {}", entry.getKey(), entry.getValue());
        }
    }
    JPPFDriverConfigurationSource.loadBalancing = new DriverLoadBalancing(configuration)
            .getLoadBalancingConfigValues();
    final ClustermeisterLauncher launcher = new ClustermeisterDriverLauncher(true);
    final AtomicBoolean initialized = new AtomicBoolean(false);
    final Monitor initializationMonitor = new Monitor(false);
    final Monitor.Guard isInitialized = new Monitor.Guard(initializationMonitor) {
        @Override
        public boolean isSatisfied() {
            return initialized.get();
        }
    };
    launcher.addObserver(new Observer() {
        @Override
        public void update(Observable o, Object arg) {
            initializationMonitor.enter();
            try {
                initialized.set(true);
            } finally {
                initializationMonitor.leave();
            }
        }
    });
    Thread driverThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                launcher.doLaunch(true, ClustermeisterProcessLauncher.StreamSink.LOG);
            } catch (Throwable ex) {
                logger.warn("Execption from local driver thread.", ex);
            }
        }
    });
    driverThread.setName(String.format("%s-%s", DRIVER_THREAD_NAME, driverThread.getId()));
    driverThread.start();

    //wait for driver to initialize.
    initializationMonitor.enter();
    try {
        try {
            initializationMonitor.waitFor(isInitialized);
        } catch (InterruptedException ex) {
            logger.warn("Interrupted while waiting for local driver to initialize! "
                    + "Initialization may not be complete.", ex);
        }
    } finally {
        initializationMonitor.leave();
    }
    return launcher;
}

From source file:com.adyrhan.networkclipboard.HttpServer.java

public HttpServer() {
    mIsRunning = new AtomicBoolean(false);
}

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   www .j a v a 2  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.netflix.curator.framework.recipes.queue.TestBoundedDistributedQueue.java

@SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
@Test/* w  w w  .ja va2 s .c o m*/
public void testMulti() throws Exception {
    final String PATH = "/queue";
    final int CLIENT_QTY = 4;
    final int MAX_ITEMS = 10;
    final int ADD_ITEMS = MAX_ITEMS * 100;
    final int SLOP_FACTOR = 2;

    final QueueConsumer<String> consumer = new QueueConsumer<String>() {
        @Override
        public void consumeMessage(String message) throws Exception {
            Thread.sleep(10);
        }

        @Override
        public void stateChanged(CuratorFramework client, ConnectionState newState) {
        }
    };

    final Timing timing = new Timing();
    final ExecutorService executor = Executors.newCachedThreadPool();
    ExecutorCompletionService<Void> completionService = new ExecutorCompletionService<Void>(executor);

    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
            timing.session(), timing.connection(), new RetryOneTime(1));
    try {
        client.start();
        client.create().forPath(PATH);

        final CountDownLatch isWaitingLatch = new CountDownLatch(1);
        final AtomicBoolean isDone = new AtomicBoolean(false);
        final List<Integer> counts = new CopyOnWriteArrayList<Integer>();
        final Object lock = new Object();
        executor.submit(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                Watcher watcher = new Watcher() {
                    @Override
                    public void process(WatchedEvent event) {
                        synchronized (lock) {
                            lock.notifyAll();
                        }
                    }
                };

                while (!Thread.currentThread().isInterrupted() && client.isStarted() && !isDone.get()) {
                    synchronized (lock) {
                        int size = client.getChildren().usingWatcher(watcher).forPath(PATH).size();
                        counts.add(size);
                        isWaitingLatch.countDown();
                        lock.wait();
                    }
                }
                return null;
            }
        });
        isWaitingLatch.await();

        for (int i = 0; i < CLIENT_QTY; ++i) {
            final int index = i;
            completionService.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    CuratorFramework client = null;
                    DistributedQueue<String> queue = null;

                    try {
                        client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
                                timing.connection(), new RetryOneTime(1));
                        client.start();
                        queue = QueueBuilder.builder(client, consumer, serializer, PATH).executor(executor)
                                .maxItems(MAX_ITEMS).putInBackground(false).lockPath("/locks").buildQueue();
                        queue.start();

                        for (int i = 0; i < ADD_ITEMS; ++i) {
                            queue.put("" + index + "-" + i);
                        }
                    } finally {
                        IOUtils.closeQuietly(queue);
                        IOUtils.closeQuietly(client);
                    }
                    return null;
                }
            });
        }

        for (int i = 0; i < CLIENT_QTY; ++i) {
            completionService.take().get();
        }

        isDone.set(true);
        synchronized (lock) {
            lock.notifyAll();
        }

        for (int count : counts) {
            Assert.assertTrue(counts.toString(), count <= (MAX_ITEMS * SLOP_FACTOR));
        }
    } finally {
        executor.shutdownNow();
        IOUtils.closeQuietly(client);
    }
}

From source file:com.kixeye.chassis.support.test.hystrix.ChassisHystrixTest.java

@Test
@SuppressWarnings("unused")
public void testCommandTimeOut() throws InterruptedException {
    final AtomicBoolean done = new AtomicBoolean(false);

    // kick off async command
    Observable<String> observable = new TestTimeOutCommand().observe();

    // Add handler
    observable.subscribe(new Observer<String>() {
        @Override/*w  ww . j  ava 2s .c  om*/
        public void onCompleted() {
            Assert.assertNull("Should not complete");
            done.set(true);
        }

        @Override
        public void onError(Throwable e) {
            done.set(true);
        }

        @Override
        public void onNext(String args) {
            Assert.assertNull("Should not get a result");
            done.set(true);
        }
    });

    // spin until done
    while (!done.get()) {
        Thread.sleep(100);
    }
}

From source file:org.lol.reddit.fragments.AddAccountDialog.java

@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {

    if (alreadyCreated)
        return getDialog();
    alreadyCreated = true;//from ww w .  ja  va2 s  .  c o  m

    super.onCreateDialog(savedInstanceState);

    final Activity activity = getSupportActivity();
    final Context appContext = activity.getApplicationContext();

    final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setTitle(R.string.accounts_add);

    final View view = activity.getLayoutInflater().inflate(R.layout.dialog_login);
    builder.setView(view);
    builder.setCancelable(true);

    final EditText usernameBox = ((EditText) view.findViewById(R.id.login_username));
    usernameBox.setText(lastUsername);
    usernameBox.requestFocus();
    usernameBox.requestFocusFromTouch();

    builder.setPositiveButton(R.string.accounts_login, new DialogInterface.OnClickListener() {
        public void onClick(final DialogInterface dialogInterface, final int i) {

            final String username = ((EditText) getDialog().findViewById(R.id.login_username)).getText()
                    .toString().trim();
            final String password = ((EditText) getDialog().findViewById(R.id.login_password)).getText()
                    .toString();

            lastUsername = username;

            final ProgressDialog progressDialog = new ProgressDialog(activity);
            final Thread thread;
            progressDialog.setTitle(R.string.accounts_loggingin);
            progressDialog.setMessage(getString(R.string.accounts_loggingin_msg));
            progressDialog.setIndeterminate(true);

            final AtomicBoolean cancelled = new AtomicBoolean(false);

            progressDialog.setCancelable(true);
            progressDialog.setCanceledOnTouchOutside(false);

            progressDialog.show();

            progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                public void onCancel(final DialogInterface dialogInterface) {
                    cancelled.set(true);
                    progressDialog.dismiss();
                }
            });

            progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                public boolean onKey(final DialogInterface dialogInterface, final int keyCode,
                        final KeyEvent keyEvent) {

                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        cancelled.set(true);
                        progressDialog.dismiss();
                    }

                    return true;
                }
            });

            thread = new Thread() {
                @Override
                public void run() {

                    // TODO better HTTP client
                    final RedditAccount.LoginResultPair result = RedditAccount.login(appContext, username,
                            password, new DefaultHttpClient());

                    General.UI_THREAD_HANDLER.post(new Runnable() {
                        public void run() {

                            if (cancelled.get())
                                return; // safe, since we're in the UI thread

                            progressDialog.dismiss();

                            final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(activity);
                            alertBuilder.setNeutralButton(R.string.dialog_close,
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            new AccountListDialog().show(activity);
                                        }
                                    });

                            // TODO handle errors better
                            switch (result.result) {
                            case CONNECTION_ERROR:
                                alertBuilder.setTitle(appContext.getString(R.string.error_connection_title));
                                alertBuilder.setMessage(appContext.getString(R.string.message_cannotlogin));
                                break;
                            case INTERNAL_ERROR:
                                alertBuilder.setTitle(appContext.getString(R.string.error_unknown_title));
                                alertBuilder.setMessage(appContext.getString(R.string.message_cannotlogin));
                                break;
                            case JSON_ERROR:
                                alertBuilder.setTitle(appContext.getString(R.string.error_parse_title));
                                alertBuilder.setMessage(appContext.getString(R.string.message_cannotlogin));
                                break;
                            case REQUEST_ERROR:
                                alertBuilder.setTitle(appContext.getString(R.string.error_connection_title));
                                alertBuilder.setMessage(appContext.getString(R.string.message_cannotlogin));
                                break;
                            case UNKNOWN_REDDIT_ERROR:
                                alertBuilder.setTitle(appContext.getString(R.string.error_unknown_title));
                                alertBuilder.setMessage(appContext.getString(R.string.message_cannotlogin));
                                break;
                            case WRONG_PASSWORD:
                                alertBuilder
                                        .setTitle(appContext.getString(R.string.error_invalid_password_title));
                                alertBuilder.setMessage(
                                        appContext.getString(R.string.error_invalid_password_message));
                                break;
                            case RATELIMIT:
                                alertBuilder.setTitle(appContext.getString(R.string.error_ratelimit_title));
                                alertBuilder.setMessage(String.format("%s \"%s\"",
                                        appContext.getString(R.string.error_ratelimit_message),
                                        result.extraMessage));
                                break;
                            case SUCCESS:
                                RedditAccountManager.getInstance(appContext).addAccount(result.account);
                                RedditAccountManager.getInstance(appContext).setDefaultAccount(result.account);
                                alertBuilder.setTitle(appContext.getString(R.string.general_success));
                                alertBuilder.setMessage(appContext.getString(R.string.message_nowloggedin));
                                lastUsername = "";
                                break;
                            default:
                                throw new RuntimeException();
                            }

                            final AlertDialog alertDialog = alertBuilder.create();
                            alertDialog.show();
                        }
                    });
                }
            };

            thread.start();
        }
    });

    builder.setNegativeButton(R.string.dialog_cancel, null);

    return builder.create();
}

From source file:org.lendingclub.mercator.solarwinds.SolarwindsScanner.java

public void getNodeInformation() {
    try {/*from   www .  j av a2s  .c  o  m*/
        ObjectNode response = querySolarwinds("SELECT Nodes.NodeID, Nodes.SysName, Nodes.Caption, "
                + "Nodes.Description, Nodes.IOSVersion, Nodes.CustomProperties.SerialNumber, Nodes.MachineType, "
                + "Nodes.Vendor, Nodes.IPAddress, Nodes.SysObjectID, Nodes.DNS, Nodes.ObjectSubType, "
                + "Nodes.Status, Nodes.StatusDescription, Nodes.CustomProperties.Department, Nodes.Location,"
                + " Nodes.CustomProperties.City FROM Orion.Nodes ORDER BY Nodes.SysName");

        AtomicLong earlistUpdate = new AtomicLong(Long.MAX_VALUE);
        AtomicBoolean error = new AtomicBoolean(false);
        response.path("results").forEach(v -> {
            try {
                //solarwindsID is the hashedURL+nodeID
                getProjector().getNeoRxClient().execCypher(
                        "merge(a: SolarwindsNode {solarwindsID:{solarwindsID}}) set a+={props}, a.updateTs=timestamp() return a",
                        "solarwindsID", solarwindsScannerBuilder.hashURL + v.path("NodeID"), "props",
                        flattenNode(v)).blockingFirst(MissingNode.getInstance());
            } catch (Exception e) {
                logger.warn("problem", e);
                error.set(true);
            }

        });
        if (error.get() == false) {
            getNeoRxClient().execCypher(
                    "match(a: SolarwindsNode) where a.solarwindsID={solarwindsID} and  a.updateTs<{cutoff} detach delete a",
                    "solarwindsID", solarwindsScannerBuilder.hashURL, "cutoff", earlistUpdate.get());
        }
    } catch (Exception e) {
        logger.info(e.toString());
    }
}

From source file:com.spotify.helios.servicescommon.coordination.DefaultZooKeeperClient.java

public DefaultZooKeeperClient(final CuratorFramework client, final String clusterId) {
    this.client = client;
    this.clusterId = clusterId;

    if (clusterId == null) {
        this.clusterIdExists = null;
        this.watcher = null;
        this.connectionStateListener = null;
        return;//from   www  .  j  a va2 s . c  om
    }

    this.clusterIdExists = new AtomicBoolean(false);

    this.watcher = new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            log.info("DefaultZooKeeperClient processing WatchedEvent - {}", event);
            checkClusterIdExists(clusterId, "watcher");
        }
    };

    connectionStateListener = new ConnectionStateListener() {
        @Override
        public void stateChanged(CuratorFramework client, ConnectionState newState) {
            log.info("DefaultZooKeeperClient connection state change - {}", newState);
            if (newState == ConnectionState.RECONNECTED) {
                checkClusterIdExists(clusterId, "connectionStateListener");
            }
        }
    };
}

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 w w. j a  va2  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");
    }
}