List of usage examples for java.util.concurrent.atomic AtomicBoolean AtomicBoolean
public AtomicBoolean(boolean initialValue)
From source file:com.netflix.curator.framework.recipes.leader.TestLeaderLatch.java
@Test public void testWaiting() throws Exception { final int PARTICIPANT_QTY = 10; ExecutorService executorService = Executors.newFixedThreadPool(PARTICIPANT_QTY); ExecutorCompletionService<Void> service = new ExecutorCompletionService<Void>(executorService); final Timing timing = new Timing(); final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try {//from www.j a va 2 s. c o m client.start(); final AtomicBoolean thereIsALeader = new AtomicBoolean(false); for (int i = 0; i < PARTICIPANT_QTY; ++i) { service.submit(new Callable<Void>() { @Override public Void call() throws Exception { LeaderLatch latch = new LeaderLatch(client, PATH_NAME); try { latch.start(); Assert.assertTrue(latch.await(timing.forWaiting().seconds(), TimeUnit.SECONDS)); Assert.assertTrue(thereIsALeader.compareAndSet(false, true)); Thread.sleep((int) (10 * Math.random())); } finally { thereIsALeader.set(false); latch.close(); } return null; } }); } for (int i = 0; i < PARTICIPANT_QTY; ++i) { service.take().get(); } } finally { executorService.shutdown(); IOUtils.closeQuietly(client); } }
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 2s.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: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/*w w w . j a v a2 s. c o 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.spectralogic.ds3client.helpers.FileObjectPutter_Test.java
@Test public void testThatNamedPipeThrows() throws IOException, InterruptedException { Assume.assumeFalse(Platform.isWindows()); final String tempPathPrefix = null; final Path tempDirectory = Files.createTempDirectory(Paths.get("."), tempPathPrefix); final String FIFO_NAME = "bFifo"; final AtomicBoolean caughtException = new AtomicBoolean(false); try {// w w w.ja va2 s. co m Runtime.getRuntime().exec("mkfifo " + Paths.get(tempDirectory.toString(), FIFO_NAME)).waitFor(); new FileObjectPutter(tempDirectory).buildChannel(FIFO_NAME); } catch (final UnrecoverableIOException e) { assertTrue(e.getMessage().contains(FIFO_NAME)); caughtException.set(true); } finally { FileUtils.deleteDirectory(tempDirectory.toFile()); } assertTrue(caughtException.get()); }
From source file:ch.cyberduck.core.local.FinderLocalTest.java
@Test public void testReleaseSecurityScopeBookmarkInputStreamClose() throws Exception { final AtomicBoolean released = new AtomicBoolean(false); FinderLocal l = new FinderLocal(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()) { @Override//from w ww .j a va 2s .com public void release(final Object lock) { released.set(true); super.release(lock); } }; new DefaultLocalTouchFeature().touch(l); final InputStream in = l.getInputStream(); in.close(); assertTrue(released.get()); l.delete(); }
From source file:com.tascape.qa.th.android.driver.App.java
/** * The method starts a GUI to let an user inspect element tree and take screenshot when the user is interacting * with the app-under-test manually. Please make sure to set timeout long enough for manual interaction. * * @param timeoutMinutes timeout in minutes to fail the manual steps * * @throws Exception if case of error//from w ww . ja v a2s. c o m */ public void interactManually(int timeoutMinutes) throws Exception { LOG.info("Start manual UI interaction"); long end = System.currentTimeMillis() + timeoutMinutes * 60000L; AtomicBoolean visible = new AtomicBoolean(true); AtomicBoolean pass = new AtomicBoolean(false); String tName = Thread.currentThread().getName() + "m"; SwingUtilities.invokeLater(() -> { JDialog jd = new JDialog((JFrame) null, "Manual Device UI Interaction - " + device.getProductDetail()); jd.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); JPanel jpContent = new JPanel(new BorderLayout()); jd.setContentPane(jpContent); jpContent.setPreferredSize(new Dimension(1088, 828)); jpContent.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); JPanel jpInfo = new JPanel(); jpContent.add(jpInfo, BorderLayout.PAGE_START); jpInfo.setLayout(new BorderLayout()); { JButton jb = new JButton("PASS"); jb.setForeground(Color.green.darker()); jb.setFont(jb.getFont().deriveFont(Font.BOLD)); jpInfo.add(jb, BorderLayout.LINE_START); jb.addActionListener(event -> { pass.set(true); jd.dispose(); visible.set(false); }); } { JButton jb = new JButton("FAIL"); jb.setForeground(Color.red); jb.setFont(jb.getFont().deriveFont(Font.BOLD)); jpInfo.add(jb, BorderLayout.LINE_END); jb.addActionListener(event -> { pass.set(false); jd.dispose(); visible.set(false); }); } JLabel jlTimeout = new JLabel("xxx seconds left", SwingConstants.CENTER); jpInfo.add(jlTimeout, BorderLayout.CENTER); jpInfo.add(jlTimeout, BorderLayout.CENTER); new SwingWorker<Long, Long>() { @Override protected Long doInBackground() throws Exception { while (System.currentTimeMillis() < end) { Thread.sleep(1000); long left = (end - System.currentTimeMillis()) / 1000; this.publish(left); } return 0L; } @Override protected void process(List<Long> chunks) { Long l = chunks.get(chunks.size() - 1); jlTimeout.setText(l + " seconds left"); if (l < 850) { jlTimeout.setForeground(Color.red); } } }.execute(); JPanel jpResponse = new JPanel(new BorderLayout()); JPanel jpProgress = new JPanel(new BorderLayout()); jpResponse.add(jpProgress, BorderLayout.PAGE_START); JTextArea jtaJson = new JTextArea(); jtaJson.setEditable(false); jtaJson.setTabSize(4); Font font = jtaJson.getFont(); jtaJson.setFont(new Font("Courier New", font.getStyle(), font.getSize())); JTree jtView = new JTree(); JTabbedPane jtp = new JTabbedPane(); jtp.add("tree", new JScrollPane(jtView)); jtp.add("json", new JScrollPane(jtaJson)); jpResponse.add(jtp, BorderLayout.CENTER); JPanel jpScreen = new JPanel(); jpScreen.setMinimumSize(new Dimension(200, 200)); jpScreen.setLayout(new BoxLayout(jpScreen, BoxLayout.PAGE_AXIS)); JScrollPane jsp1 = new JScrollPane(jpScreen); jpResponse.add(jsp1, BorderLayout.LINE_START); JPanel jpJs = new JPanel(new BorderLayout()); JTextArea jtaJs = new JTextArea(); jpJs.add(new JScrollPane(jtaJs), BorderLayout.CENTER); JSplitPane jSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, jpResponse, jpJs); jSplitPane.setResizeWeight(0.88); jpContent.add(jSplitPane, BorderLayout.CENTER); JPanel jpLog = new JPanel(); jpLog.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0)); jpLog.setLayout(new BoxLayout(jpLog, BoxLayout.LINE_AXIS)); JCheckBox jcbTap = new JCheckBox("Enable Click", null, false); jpLog.add(jcbTap); jpLog.add(Box.createHorizontalStrut(8)); JButton jbLogUi = new JButton("Log Screen"); jpResponse.add(jpLog, BorderLayout.PAGE_END); { jpLog.add(jbLogUi); jbLogUi.addActionListener((ActionEvent event) -> { jtaJson.setText("waiting for screenshot..."); Thread t = new Thread(tName) { @Override public void run() { LOG.debug("\n\n"); try { WindowHierarchy wh = device.loadWindowHierarchy(); jtView.setModel(getModel(wh)); jtaJson.setText(""); jtaJson.append(wh.root.toJson().toString(2)); jtaJson.append("\n"); File png = device.takeDeviceScreenshot(); BufferedImage image = ImageIO.read(png); int w = device.getDisplayWidth(); int h = device.getDisplayHeight(); BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = resizedImg.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(image, 0, 0, w, h, null); g2.dispose(); JLabel jLabel = new JLabel(new ImageIcon(resizedImg)); jpScreen.removeAll(); jsp1.setPreferredSize(new Dimension(w + 30, h)); jpScreen.add(jLabel); jLabel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { LOG.debug("clicked at {},{}", e.getPoint().getX(), e.getPoint().getY()); if (jcbTap.isSelected()) { device.click(e.getPoint().x, e.getPoint().y); device.waitForIdle(); jbLogUi.doClick(); } } }); } catch (Exception ex) { LOG.error("Cannot log screen", ex); jtaJson.append("Cannot log screen"); } jtaJson.append("\n\n\n"); LOG.debug("\n\n"); jd.setSize(jd.getBounds().width + 1, jd.getBounds().height + 1); jd.setSize(jd.getBounds().width - 1, jd.getBounds().height - 1); } }; t.start(); }); } jpLog.add(Box.createHorizontalStrut(38)); { JButton jbLogMsg = new JButton("Log Message"); jpLog.add(jbLogMsg); JTextField jtMsg = new JTextField(10); jpLog.add(jtMsg); jtMsg.addFocusListener(new FocusListener() { @Override public void focusLost(final FocusEvent pE) { } @Override public void focusGained(final FocusEvent pE) { jtMsg.selectAll(); } }); jtMsg.addKeyListener(new KeyAdapter() { @Override public void keyPressed(java.awt.event.KeyEvent e) { if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { jbLogMsg.doClick(); } } }); jbLogMsg.addActionListener(event -> { Thread t = new Thread(tName) { @Override public void run() { String msg = jtMsg.getText(); if (StringUtils.isNotBlank(msg)) { LOG.info("{}", msg); jtMsg.selectAll(); } } }; t.start(); try { t.join(); } catch (InterruptedException ex) { LOG.error("Cannot take screenshot", ex); } jtMsg.requestFocus(); }); } jpLog.add(Box.createHorizontalStrut(38)); { JButton jbClear = new JButton("Clear"); jpLog.add(jbClear); jbClear.addActionListener(event -> { jtaJson.setText(""); }); } JPanel jpAction = new JPanel(); jpContent.add(jpAction, BorderLayout.PAGE_END); jpAction.setLayout(new BoxLayout(jpAction, BoxLayout.LINE_AXIS)); jpJs.add(jpAction, BorderLayout.PAGE_END); jd.pack(); jd.setVisible(true); jd.setLocationRelativeTo(null); jbLogUi.doClick(); }); while (visible.get()) { if (System.currentTimeMillis() > end) { LOG.error("Manual UI interaction timeout"); break; } Thread.sleep(500); } if (pass.get()) { LOG.info("Manual UI Interaction returns PASS"); } else { Assert.fail("Manual UI Interaction returns FAIL"); } }
From source file:org.venice.piazza.servicecontroller.messaging.ServiceMessageThreadManagerTest.java
/** * Test Abort Polling losed Connection// ww w .j av a2 s . c o m */ public void testAbortPollingClosedConnection() { final ServiceMessageThreadManager smtmMock = Mockito.spy(smtManager); try { Mockito.doReturn(new AtomicBoolean(true)).when(smtmMock).makeAtomicBoolean(); smtmMock.pollAbortServiceJobs(); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessMutexBase.java
@Test public void testReentrantSingleLock() throws Exception { final int THREAD_QTY = 10; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start();/* w ww. java2 s . co m*/ try { final AtomicBoolean hasLock = new AtomicBoolean(false); final AtomicBoolean isFirst = new AtomicBoolean(true); final Semaphore semaphore = new Semaphore(1); final InterProcessLock mutex = makeLock(client); List<Future<Object>> threads = Lists.newArrayList(); ExecutorService service = Executors.newCachedThreadPool(); for (int i = 0; i < THREAD_QTY; ++i) { Future<Object> t = service.submit(new Callable<Object>() { @Override public Object call() throws Exception { semaphore.acquire(); mutex.acquire(); Assert.assertTrue(hasLock.compareAndSet(false, true)); try { if (isFirst.compareAndSet(true, false)) { semaphore.release(THREAD_QTY - 1); while (semaphore.availablePermits() > 0) { Thread.sleep(100); } } else { Thread.sleep(100); } } finally { mutex.release(); hasLock.set(false); } return null; } }); threads.add(t); } for (Future<Object> t : threads) { t.get(); } } finally { client.close(); } }
From source file:com.impetus.client.kudu.schemamanager.KuduDBSchemaManager.java
@Override protected void update(List<TableInfo> tableInfos) { for (TableInfo tableInfo : tableInfos) { try {//ww w . j a v a2 s .co m if (!client.tableExists(tableInfo.getTableName())) { createKuduTable(tableInfo); } else { List<String> entityColumns = new ArrayList<String>(); KuduTable table = client.openTable(tableInfo.getTableName()); AlterTableOptions alterTableOptions = new AlterTableOptions(); AtomicBoolean updated = new AtomicBoolean(false); Schema schema = table.getSchema(); // add modify columns for (ColumnInfo columnInfo : tableInfo.getColumnMetadatas()) { entityColumns.add(columnInfo.getColumnName()); alterColumn(alterTableOptions, schema, columnInfo, updated); } // update for embeddables logic for (EmbeddedColumnInfo embColumnInfo : tableInfo.getEmbeddedColumnMetadatas()) { for (ColumnInfo columnInfo : embColumnInfo.getColumns()) { entityColumns.add(columnInfo.getColumnName()); alterColumn(alterTableOptions, schema, columnInfo, updated); } } // delete columns for (ColumnSchema columnSchema : schema.getColumns()) { // if not in tableInfo and not a key then delete if (!entityColumns.contains(columnSchema.getName()) && !columnSchema.isKey()) { alterTableOptions.dropColumn(columnSchema.getName()); updated.set(true); } } if (updated.get()) { client.alterTable(tableInfo.getTableName(), alterTableOptions); } } } catch (Exception e) { logger.error("Error while updating tables, Caused by: " + e.getMessage()); throw new KunderaException("Error while updating tables, Caused by: " + e.getMessage()); } } }
From source file:biz.ganttproject.impex.csv.CsvImportTest.java
public void testSkipLinesWithEmptyMandatoryFields() throws IOException { String header = "A, B, C"; String data1 = "a1,,c1"; String data2 = "a2,b2,c2"; String data3 = ",b3,c3"; final AtomicBoolean wasCalled = new AtomicBoolean(false); RecordGroup recordGroup = new RecordGroup("ABC", ImmutableSet.<String>of("A", "B", "C"), ImmutableSet.<String>of("A", "B")) { @Override/*from w ww .ja v a 2s. c om*/ protected boolean doProcess(CSVRecord record) { if (!super.doProcess(record)) { return false; } if (!hasMandatoryFields(record)) { return false; } wasCalled.set(true); assertEquals("a2", record.get("A")); assertEquals("b2", record.get("B")); return true; } }; GanttCSVOpen importer = new GanttCSVOpen(createSupplier(Joiner.on('\n').join(header, data1, data2, data3)), recordGroup); importer.load(); assertTrue(wasCalled.get()); assertEquals(2, importer.getSkippedLineCount()); }