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

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

Introduction

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

Prototype

public final boolean get() 

Source Link

Document

Returns the current value, with memory effects as specified by VarHandle#getVolatile .

Usage

From source file:com.netflix.dyno.connectionpool.impl.lb.CircularListTest.java

@Test
public void testMultipleThreads() throws Exception {

    final AtomicBoolean stop = new AtomicBoolean(false);
    final CyclicBarrier barrier = new CyclicBarrier(5);
    final List<Future<Map<Integer, Integer>>> futures = new ArrayList<Future<Map<Integer, Integer>>>();

    for (int i = 0; i < 5; i++) {
        futures.add(threadPool.submit(new Callable<Map<Integer, Integer>>() {

            @Override//from  w  ww.j a va2 s.c  om
            public Map<Integer, Integer> call() throws Exception {

                barrier.await();

                TestWorker worker = new TestWorker();

                while (!stop.get()) {
                    worker.process();
                }

                return worker.map;
            }
        }));
    }

    Thread.sleep(200);
    stop.set(true);

    Map<Integer, Integer> totalMap = getTotalMap(futures);
    checkValues(new ArrayList<Integer>(totalMap.values()));
}

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

@Test
public void testCancelMapTask() {
    addInput(new InfiniteInputIterator());
    setOutput(new DiscardingOutputCollector<Record>());

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

    final AtomicBoolean success = new AtomicBoolean(false);

    final Thread taskRunner = new Thread() {
        @Override//www  . j  a  v  a  2 s.  c  om
        public void run() {
            try {
                testDriver(testTask, MockMapStub.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:org.apache.hadoop.hbase.master.TestZKBasedCloseRegion.java

@Test(timeout = 300000)
public void testCloseRegion() throws Exception {
    LOG.info("Running testCloseRegion");
    MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster();
    LOG.info("Number of region servers = " + cluster.getLiveRegionServerThreads().size());

    int rsIdx = 0;
    HRegionServer regionServer = TEST_UTIL.getHBaseCluster().getRegionServer(rsIdx);
    Collection<HRegion> regions = regionServer.getOnlineRegions();
    HRegion region = regions.iterator().next();
    LOG.debug("Asking RS to close region " + region.getRegionNameAsString());

    AtomicBoolean closeEventProcessed = new AtomicBoolean(false);
    RegionServerOperationListener listener = new CloseRegionEventListener(region.getRegionNameAsString(),
            closeEventProcessed);//from w  ww  .java  2s  .  c  o  m
    HMaster master = TEST_UTIL.getHBaseCluster().getMaster();
    master.getRegionServerOperationQueue().registerRegionServerOperationListener(listener);
    HMsg closeRegionMsg = new HMsg(HMsg.Type.MSG_REGION_CLOSE, region.getRegionInfo(),
            Bytes.toBytes("Forcing close in test"));
    TEST_UTIL.getHBaseCluster().addMessageToSendRegionServer(rsIdx, closeRegionMsg);

    synchronized (closeEventProcessed) {
        // wait for 3 minutes
        closeEventProcessed.wait(3 * 60 * 1000);
    }
    if (!closeEventProcessed.get()) {
        throw new Exception("Timed out, close event not called on master.");
    } else {
        LOG.info("Done with test, RS informed master successfully.");
    }
}

From source file:de.willuhn.jameica.hbci.passports.pintan.ChipTANDialog.java

/**
* @see de.willuhn.jameica.gui.dialogs.PasswordDialog#paint(org.eclipse.swt.widgets.Composite)
*//*from   ww w. j  av a2 s  . com*/
protected void paint(final Composite parent) throws Exception {
    Container container = new SimpleContainer(parent);

    if (this.usb) {
        Application.getMessagingFactory().sendMessage(new StatusBarMessage(
                i18n.tr("Legen Sie die bitte Chipkarte ein."), StatusBarMessage.TYPE_INFO));

        this.setShowPassword(true); // Bei ChipTAN USB immer die TAN anzeigen, damit der User vergleichen kann.
        container.addHeadline(i18n.tr("ChipTAN USB"));
        container.addText(i18n.tr(
                "Legen Sie die Chipkarte ein und folgen Sie den Anweisungen des Kartenlesers. Klicken Sie auf \"OK\", wenn die TAN korrekt bertragen wurde."),
                true);

        ProgressBar progress = new ProgressBar(container.getComposite(), SWT.INDETERMINATE);
        final GridData gd = new GridData(GridData.FILL_HORIZONTAL);
        gd.horizontalSpan = 2;
        progress.setLayoutData(gd);

        final AtomicBoolean cancelled = new AtomicBoolean(false);

        final Thread usbThread = new Thread() {
            public void run() {
                try {
                    Logger.info("trying to get TAN using USB cardreader");
                    String s = StringUtils.trimToNull(service.getTan(code));
                    if (s != null && !cancelled.get()) {
                        setPassword(s, parent);
                    } else {
                        throw new Exception(i18n.tr("Keine TAN bertragen"));
                    }
                } catch (Exception e) {
                    if (!cancelled.get()) {
                        Logger.error("unable to get tan from chipcard", e);
                        setErrorText(i18n.tr("Fehler bei TAN-Ermittlung: {0}", e.getMessage()));
                    }
                }
            }
        };
        usbThread.start();

        parent.addDisposeListener(new DisposeListener() {
            @Override
            public void widgetDisposed(DisposeEvent e) {
                cancelled.set(true);
                // Nur fuer den Fall, dass der Thread noch laeuft.
                try {
                    if (usbThread != null)
                        usbThread.interrupt();
                } catch (Throwable th) {
                    Logger.error("unable to interrupt USB thread", th);
                }
            }
        });
    } else {
        container.addHeadline(i18n.tr(this.usb ? "ChipTAN USB" : "Flicker-Grafik"));
        container.addText(i18n.tr("Klicken Sie \"-\" bzw. \"+\", um die Breite anzupassen."), true);
        FlickerPart flicker = new FlickerPart(this.code);
        flicker.paint(parent);
    }

    // Hier stehen dann noch die Anweisungen von der Bank drin
    super.paint(parent);

    if (!this.usb) {
        // Wir muessen das Fenster wenigstens gross genug machen, damit der Flickercode reinpasst, falls
        // der User den recht verbreitert hat
        int width = settings.getInt("width", -1);
        if (width > 0)
            width += 10; // Wenigstens noch 10 Pixel Rand hinzufuegen.
        // Wir nehmen den groesseren von beiden Werten

        getShell().setMinimumSize(getShell().computeSize(width > WINDOW_WIDTH ? width : WINDOW_WIDTH,
                smallDisplay ? 520 : SWT.DEFAULT));
    }
}

From source file:gobblin.couchbase.writer.CouchbaseWriter.java

@Override
public Future<WriteResponse> write(final D record, final WriteCallback callback) {
    assertRecordWritable(record);//from  w  w w  .jav a  2  s.  c  o m
    if (record instanceof TupleDocument) {
        ((TupleDocument) record).content().value1().retain();
    }
    Observable<D> observable = _bucket.async().upsert(record);
    if (callback == null) {
        return new WriteResponseFuture<>(
                observable.timeout(_operationTimeout, _operationTimeunit).toBlocking().toFuture(),
                _defaultWriteResponseMapper);
    } else {

        final AtomicBoolean callbackFired = new AtomicBoolean(false);
        final BlockingQueue<Pair<WriteResponse, Throwable>> writeResponseQueue = new ArrayBlockingQueue<>(1);

        final Future<WriteResponse> writeResponseFuture = new Future<WriteResponse>() {
            @Override
            public boolean cancel(boolean mayInterruptIfRunning) {
                return false;
            }

            @Override
            public boolean isCancelled() {
                return false;
            }

            @Override
            public boolean isDone() {
                return callbackFired.get();
            }

            @Override
            public WriteResponse get() throws InterruptedException, ExecutionException {
                Pair<WriteResponse, Throwable> writeResponseThrowablePair = writeResponseQueue.take();
                return getWriteResponseorThrow(writeResponseThrowablePair);
            }

            @Override
            public WriteResponse get(long timeout, TimeUnit unit)
                    throws InterruptedException, ExecutionException, TimeoutException {
                Pair<WriteResponse, Throwable> writeResponseThrowablePair = writeResponseQueue.poll(timeout,
                        unit);
                if (writeResponseThrowablePair == null) {
                    throw new TimeoutException("Timeout exceeded while waiting for future to be done");
                } else {
                    return getWriteResponseorThrow(writeResponseThrowablePair);
                }
            }
        };

        observable.timeout(_operationTimeout, _operationTimeunit).subscribe(new Subscriber<D>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                callbackFired.set(true);
                writeResponseQueue.add(new Pair<WriteResponse, Throwable>(null, e));
                callback.onFailure(e);
            }

            @Override
            public void onNext(D doc) {
                try {
                    callbackFired.set(true);
                    WriteResponse writeResponse = new GenericWriteResponse<D>(doc);
                    writeResponseQueue.add(new Pair<WriteResponse, Throwable>(writeResponse, null));
                    callback.onSuccess(writeResponse);
                } finally {
                    if (doc instanceof TupleDocument) {
                        ((TupleDocument) doc).content().value1().release();
                    }
                }
            }
        });
        return writeResponseFuture;
    }
}

From source file:org.apache.solr.handler.dataimport.XPathEntityProcessor.java

private Iterator<Map<String, Object>> getRowIterator(final Reader data, final String s) {
    //nothing atomic about it. I just needed a StongReference
    final AtomicReference<Exception> exp = new AtomicReference<>();
    final BlockingQueue<Map<String, Object>> blockingQueue = new ArrayBlockingQueue<>(blockingQueueSize);
    final AtomicBoolean isEnd = new AtomicBoolean(false);
    final AtomicBoolean throwExp = new AtomicBoolean(true);
    publisherThread = new Thread() {
        @Override/*from ww w .  j a  v  a2 s  . c o m*/
        public void run() {
            try {
                xpathReader.streamRecords(data, (record, xpath) -> {
                    if (isEnd.get()) {
                        throwExp.set(false);
                        //To end the streaming . otherwise the parsing will go on forever
                        //though consumer has gone away
                        throw new RuntimeException("BREAK");
                    }
                    Map<String, Object> row;
                    try {
                        row = readRow(record, xpath);
                    } catch (Exception e) {
                        isEnd.set(true);
                        return;
                    }
                    offer(row);
                });
            } catch (Exception e) {
                if (throwExp.get())
                    exp.set(e);
            } finally {
                closeIt(data);
                if (!isEnd.get()) {
                    offer(END_MARKER);
                }
            }
        }

        private void offer(Map<String, Object> row) {
            try {
                while (!blockingQueue.offer(row, blockingQueueTimeOut, blockingQueueTimeOutUnits)) {
                    if (isEnd.get())
                        return;
                    LOG.debug("Timeout elapsed writing records.  Perhaps buffer size should be increased.");
                }
            } catch (InterruptedException e) {
                return;
            } finally {
                synchronized (this) {
                    notifyAll();
                }
            }
        }
    };

    publisherThread.start();

    return new Iterator<Map<String, Object>>() {
        private Map<String, Object> lastRow;
        int count = 0;

        @Override
        public boolean hasNext() {
            return !isEnd.get();
        }

        @Override
        public Map<String, Object> next() {
            Map<String, Object> row;

            do {
                try {
                    row = blockingQueue.poll(blockingQueueTimeOut, blockingQueueTimeOutUnits);
                    if (row == null) {
                        LOG.debug("Timeout elapsed reading records.");
                    }
                } catch (InterruptedException e) {
                    LOG.debug("Caught InterruptedException while waiting for row.  Aborting.");
                    isEnd.set(true);
                    return null;
                }
            } while (row == null);

            if (row == END_MARKER) {
                isEnd.set(true);
                if (exp.get() != null) {
                    String msg = "Parsing failed for xml, url:" + s + " rows processed in this xml:" + count;
                    if (lastRow != null)
                        msg += " last row in this xml:" + lastRow;
                    if (ABORT.equals(onError)) {
                        wrapAndThrow(SEVERE, exp.get(), msg);
                    } else if (SKIP.equals(onError)) {
                        wrapAndThrow(DataImportHandlerException.SKIP, exp.get());
                    } else {
                        LOG.warn(msg, exp.get());
                    }
                }
                return null;
            }
            count++;
            return lastRow = row;
        }

        @Override
        public void remove() {
            /*no op*/
        }
    };

}

From source file:com.netflix.dyno.connectionpool.impl.lb.CircularListTest.java

@Test
public void testMultipleThreadsWithElementAdd() throws Exception {

    final AtomicBoolean stop = new AtomicBoolean(false);
    final CyclicBarrier barrier = new CyclicBarrier(5);
    final List<Future<Map<Integer, Integer>>> futures = new ArrayList<Future<Map<Integer, Integer>>>();

    for (int i = 0; i < 5; i++) {
        futures.add(threadPool.submit(new Callable<Map<Integer, Integer>>() {

            @Override//from   www  .  java2 s.  co  m
            public Map<Integer, Integer> call() throws Exception {

                barrier.await();

                TestWorker worker = new TestWorker();

                while (!stop.get()) {
                    worker.process();
                }

                return worker.map;
            }
        }));
    }

    Thread.sleep(200);

    List<Integer> newList = new ArrayList<Integer>(iList);
    for (int i = 10; i < 15; i++) {
        newList.add(i);
    }

    cList.swapWithList(newList);

    Thread.sleep(200);
    stop.set(true);

    Map<Integer, Integer> result = getTotalMap(futures);

    Map<Integer, Integer> subMap = CollectionUtils.filterKeys(result, new Predicate<Integer>() {
        @Override
        public boolean apply(Integer input) {
            return input < 10;
        }
    });

    checkValues(new ArrayList<Integer>(subMap.values()));

    subMap = CollectionUtils.difference(result, subMap).entriesOnlyOnLeft();
    checkValues(new ArrayList<Integer>(subMap.values()));
}

From source file:com.netflix.dyno.connectionpool.impl.lb.CircularListTest.java

@Test
public void testMultipleThreadsWithElementsRemoved() throws Exception {

    final AtomicBoolean stop = new AtomicBoolean(false);
    final CyclicBarrier barrier = new CyclicBarrier(5);
    final List<Future<Map<Integer, Integer>>> futures = new ArrayList<Future<Map<Integer, Integer>>>();

    for (int i = 0; i < 5; i++) {
        futures.add(threadPool.submit(new Callable<Map<Integer, Integer>>() {

            @Override//from   ww w .  ja va 2  s .  co m
            public Map<Integer, Integer> call() throws Exception {

                barrier.await();

                TestWorker worker = new TestWorker();

                while (!stop.get()) {
                    worker.process();
                }

                return worker.map;
            }
        }));
    }

    Thread.sleep(200);

    List<Integer> newList = new ArrayList<Integer>(iList);

    final List<Integer> removedElements = new ArrayList<Integer>();
    removedElements.add(newList.remove(2));
    removedElements.add(newList.remove(5));
    removedElements.add(newList.remove(6));

    cList.swapWithList(newList);

    Thread.sleep(200);
    stop.set(true);

    Map<Integer, Integer> result = getTotalMap(futures);

    Map<Integer, Integer> subMap = CollectionUtils.filterKeys(result, new Predicate<Integer>() {

        @Override
        public boolean apply(Integer x) {
            return !removedElements.contains(x);
        }
    });

    checkValues(new ArrayList<Integer>(subMap.values()));
}

From source file:com.dragoniade.deviantart.favorites.FavoritesDownloader.java

private STATUS downloadFile(Deviation da, String downloadUrl, String filename, boolean reportError,
        YesNoAllDialog matureMoveDialog, YesNoAllDialog overwriteDialog, YesNoAllDialog overwriteNewerDialog,
        YesNoAllDialog deleteEmptyDialog) {

    AtomicBoolean download = new AtomicBoolean(true);
    File art = getFile(da, downloadUrl, filename, download, matureMoveDialog, overwriteDialog,
            overwriteNewerDialog, deleteEmptyDialog);
    if (art == null) {
        return null;
    }/*from  ww  w . ja v a2s.  com*/

    if (download.get()) {
        File parent = art.getParentFile();
        if (!parent.exists()) {
            if (!parent.mkdirs()) {
                showMessageDialog(owner, "Unable to create '" + parent.getPath() + "'.", "Error",
                        JOptionPane.ERROR_MESSAGE);
                return null;
            }
        }

        GetMethod method = new GetMethod(downloadUrl);
        try {
            int sc = -1;
            do {
                sc = client.executeMethod(method);
                requestCount++;
                if (sc != 200) {
                    if (sc == 404 || sc == 403) {
                        method.releaseConnection();
                        return STATUS.NOTFOUND;
                    } else {
                        LoggableException ex = new LoggableException(method.getResponseBodyAsString());
                        Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(),
                                ex);

                        int res = showConfirmDialog(owner,
                                "An error has occured when contacting deviantART : error " + sc
                                        + ". Try again?",
                                "Continue?", JOptionPane.YES_NO_CANCEL_OPTION);
                        if (res == JOptionPane.NO_OPTION) {
                            String text = "<br/><a style=\"color:red;\" href=\"" + da.getUrl() + "\">"
                                    + downloadUrl + " has an error" + "</a>";
                            setPaneText(text);
                            method.releaseConnection();
                            progress.incremTotal();
                            return STATUS.SKIP;
                        }
                        if (res == JOptionPane.CANCEL_OPTION) {
                            return null;
                        }
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                        }
                    }
                }
            } while (sc != 200);

            int length = (int) method.getResponseContentLength();
            int copied = 0;
            progress.setUnitMax(length);
            InputStream is = method.getResponseBodyAsStream();
            File tmpFile = new File(art.getParentFile(), art.getName() + ".tmp");
            FileOutputStream fos = new FileOutputStream(tmpFile, false);
            byte[] buffer = new byte[16184];
            int read = -1;

            while ((read = is.read(buffer)) > 0) {
                fos.write(buffer, 0, read);
                copied += read;
                progress.setUnitValue(copied);

                if (progress.isCancelled()) {
                    is.close();
                    method.releaseConnection();
                    tmpFile.delete();
                    return null;
                }
            }
            fos.close();
            method.releaseConnection();

            if (art.exists()) {
                if (!art.delete()) {
                    showMessageDialog(owner, "Unable to delete '" + art.getPath() + "'.", "Error",
                            JOptionPane.ERROR_MESSAGE);
                    return null;
                }
            }
            if (!tmpFile.renameTo(art)) {
                showMessageDialog(owner,
                        "Unable to rename '" + tmpFile.getPath() + "' to '" + art.getPath() + "'.", "Error",
                        JOptionPane.ERROR_MESSAGE);
                return null;
            }
            art.setLastModified(da.getTimestamp().getTime());
            return STATUS.DOWNLOADED;
        } catch (HttpException e) {
            showMessageDialog(owner, "Error contacting deviantART: " + e.getMessage(), "Error",
                    JOptionPane.ERROR_MESSAGE);
            return null;
        } catch (IOException e) {
            showMessageDialog(owner, "Error contacting deviantART: " + e.getMessage(), "Error",
                    JOptionPane.ERROR_MESSAGE);
            return null;
        }
    } else {
        progress.setText("Skipping file '" + filename + "' from " + da.getArtist());
        return STATUS.SKIP;
    }
}

From source file:com.jayway.restassured.examples.springmvc.controller.AutoSpringSecurityConfigurerITest.java

@Test
public void doesnt_add_spring_security_configurer_automatically_when_a_spring_security_configurer_has_been_manually_applied() {
    final AtomicBoolean filterUsed = new AtomicBoolean(false);

    given().webAppContextSetup(context, springSecurity(), springSecurity(new Filter() {
        public void init(FilterConfig filterConfig) throws ServletException {
        }/*from ww  w  .ja v a 2s  .  c  o m*/

        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            filterUsed.set(true);
            chain.doFilter(request, response);
        }

        public void destroy() {
        }
    })).postProcessors(httpBasic("username", "password")).param("name", "Johan").when().get("/secured/greeting")
            .then().statusCode(200).body("content", equalTo("Hello, Johan!"))
            .expect(authenticated().withUsername("username"));

    assertThat(filterUsed.get(), is(true));
}