List of usage examples for java.util.concurrent.atomic AtomicBoolean get
public final boolean get()
From source file:org.alfresco.repo.activities.feed.cleanup.FeedCleaner.java
public int execute() throws JobExecutionException { checkProperties();/*from w w w . j a v a 2 s . c om*/ final AtomicBoolean keepGoing = new AtomicBoolean(true); String lockToken = null; try { // Lock lockToken = jobLockService.getLock(LOCK_QNAME, LOCK_TTL); // Refresh to get callbacks JobLockRefreshCallback callback = new JobLockRefreshCallback() { @Override public void lockReleased() { keepGoing.set(false); } @Override public boolean isActive() { return keepGoing.get(); } }; jobLockService.refreshLock(lockToken, LOCK_QNAME, LOCK_TTL, callback); int cleaned = executeWithLock(keepGoing); if (logger.isDebugEnabled()) { logger.debug("Cleaned " + cleaned + " feed entries."); } } catch (LockAcquisitionException e) { if (logger.isDebugEnabled()) { logger.debug("Skipping feed cleaning. " + e.getMessage()); } } finally { keepGoing.set(false); // Notify the refresh callback that we are done if (lockToken != null) { jobLockService.releaseLock(lockToken, LOCK_QNAME); } } return 0; }
From source file:org.apache.hadoop.hbase.regionserver.wal.AbstractTestFSWAL.java
/** * Test flush for sure has a sequence id that is beyond the last edit appended. We do this by * slowing appends in the background ring buffer thread while in foreground we call flush. The * addition of the sync over HRegion in flush should fix an issue where flush was returning before * all of its appends had made it out to the WAL (HBASE-11109). * @throws IOException/*w ww .j a v a 2 s . c o m*/ * @see <a href="https://issues.apache.org/jira/browse/HBASE-11109">HBASE-11109</a> */ @Test public void testFlushSequenceIdIsGreaterThanAllEditsInHFile() throws IOException { String testName = currentTest.getMethodName(); final TableName tableName = TableName.valueOf(testName); final HRegionInfo hri = new HRegionInfo(tableName); final byte[] rowName = tableName.getName(); final HTableDescriptor htd = new HTableDescriptor(tableName); htd.addFamily(new HColumnDescriptor("f")); HRegion r = HBaseTestingUtility.createRegionAndWAL(hri, TEST_UTIL.getDefaultRootDirPath(), TEST_UTIL.getConfiguration(), htd); HBaseTestingUtility.closeRegionAndWAL(r); final int countPerFamily = 10; final AtomicBoolean goslow = new AtomicBoolean(false); NavigableMap<byte[], Integer> scopes = new TreeMap<byte[], Integer>(Bytes.BYTES_COMPARATOR); for (byte[] fam : htd.getFamiliesKeys()) { scopes.put(fam, 0); } // subclass and doctor a method. AbstractFSWAL<?> wal = newSlowWAL(FS, FSUtils.getRootDir(CONF), DIR.toString(), testName, CONF, null, true, null, null, new Runnable() { @Override public void run() { if (goslow.get()) { Threads.sleep(100); LOG.debug("Sleeping before appending 100ms"); } } }); HRegion region = HRegion.openHRegion(TEST_UTIL.getConfiguration(), TEST_UTIL.getTestFileSystem(), TEST_UTIL.getDefaultRootDirPath(), hri, htd, wal); EnvironmentEdge ee = EnvironmentEdgeManager.getDelegate(); try { List<Put> puts = null; for (HColumnDescriptor hcd : htd.getFamilies()) { puts = TestWALReplay.addRegionEdits(rowName, hcd.getName(), countPerFamily, ee, region, "x"); } // Now assert edits made it in. final Get g = new Get(rowName); Result result = region.get(g); assertEquals(countPerFamily * htd.getFamilies().size(), result.size()); // Construct a WALEdit and add it a few times to the WAL. WALEdit edits = new WALEdit(); for (Put p : puts) { CellScanner cs = p.cellScanner(); while (cs.advance()) { edits.add(cs.current()); } } // Add any old cluster id. List<UUID> clusterIds = new ArrayList<UUID>(); clusterIds.add(UUID.randomUUID()); // Now make appends run slow. goslow.set(true); for (int i = 0; i < countPerFamily; i++) { final HRegionInfo info = region.getRegionInfo(); final WALKey logkey = new WALKey(info.getEncodedNameAsBytes(), tableName, System.currentTimeMillis(), clusterIds, -1, -1, region.getMVCC(), scopes); wal.append(info, logkey, edits, true); } region.flush(true); // FlushResult.flushSequenceId is not visible here so go get the current sequence id. long currentSequenceId = region.getReadPoint(null); // Now release the appends goslow.set(false); assertTrue(currentSequenceId >= region.getReadPoint(null)); } finally { region.close(true); wal.close(); } }
From source file:com.netflix.curator.framework.recipes.queue.TestBoundedDistributedQueue.java
@SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") @Test//from w ww. ja va 2s . 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.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:// w ww. j a v a 2s. 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; }
From source file:org.apache.cayenne.access.dbsync.BaseSchemaUpdateStrategy_ConcurrencyTest.java
@Test public void testUpdateSchema_Concurrency() throws InterruptedException, ExecutionException, TimeoutException { final AtomicInteger counter = new AtomicInteger(); final AtomicBoolean errors = new AtomicBoolean(false); final BaseSchemaUpdateStrategy strategy = new BaseSchemaUpdateStrategy() { @Override/* w ww. ja v a 2s . c o m*/ protected void processSchemaUpdate(DataNode dataNode) throws SQLException { counter.incrementAndGet(); } }; Collection<Future<?>> tasks = new ArrayList<>(); for (int i = 0; i < 20; i++) { tasks.add(threadPool.submit(new Runnable() { @Override public void run() { try { strategy.updateSchema(dataNode); } catch (Throwable e) { LOGGER.error("error in test", e); errors.set(true); } } })); } for (Future<?> f : tasks) { f.get(1, TimeUnit.SECONDS); } assertFalse(errors.get()); assertEquals(1, counter.get()); }
From source file:org.apache.hadoop.hbase.master.TestZKBasedReopenRegion.java
@Test(timeout = 300000) public void testOpenRegion() throws Exception { 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); AtomicBoolean reopenEventProcessed = new AtomicBoolean(false); RegionServerOperationListener listener = new ReopenRegionEventListener(region.getRegionNameAsString(), closeEventProcessed, reopenEventProcessed); 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) { closeEventProcessed.wait(3 * 60 * 1000); }/*from www . j av a2 s .c o m*/ if (!closeEventProcessed.get()) { throw new Exception("Timed out, close event not called on master."); } synchronized (reopenEventProcessed) { reopenEventProcessed.wait(3 * 60 * 1000); } if (!reopenEventProcessed.get()) { throw new Exception("Timed out, open event not called on master after region close."); } LOG.info("Done with test, RS informed master successfully."); }
From source file:org.apache.jackrabbit.oak.spi.blob.AbstractBlobStoreTest.java
@Test public void testExceptionWhileReading() throws Exception { final AtomicBoolean closed = new AtomicBoolean(); InputStream in = new InputStream() { @Override// w w w. ja v a 2s. co m public void close() { closed.set(true); } @Override public int read() throws IOException { throw new RuntimeException("abc"); } }; try { store.writeBlob(in); } catch (Exception e) { String msg = e.getMessage(); assertTrue(msg, msg.indexOf("abc") >= 0); } assertTrue(closed.get()); }
From source file:org.apache.jackrabbit.oak.plugins.segment.CompactionAndCleanupIT.java
/** * Regression test for OAK-2192 testing for mixed segments. This test does not * cover OAK-3348. I.e. it does not assert the segment graph is free of cross * gc generation references.// ww w . j a va 2s . c o m */ @Test public void testMixedSegments() throws Exception { FileStore store = FileStore.builder(getFileStoreFolder()).withMaxFileSize(2).withMemoryMapping(true) .build(); final SegmentNodeStore nodeStore = SegmentNodeStore.builder(store).build(); final AtomicBoolean compactionSuccess = new AtomicBoolean(true); CompactionStrategy strategy = new CompactionStrategy(true, false, CLEAN_NONE, 0, (byte) 5) { @Override public boolean compacted(Callable<Boolean> setHead) throws Exception { compactionSuccess.set(nodeStore.locked(setHead, 1, MINUTES)); return compactionSuccess.get(); } }; strategy.setForceAfterFail(true); store.setCompactionStrategy(strategy); NodeBuilder root = nodeStore.getRoot().builder(); createNodes(root.setChildNode("test"), 10, 3); nodeStore.merge(root, EmptyHook.INSTANCE, CommitInfo.EMPTY); final Set<UUID> beforeSegments = new HashSet<UUID>(); collectSegments(store.getHead(), beforeSegments); final AtomicReference<Boolean> run = new AtomicReference<Boolean>(true); final List<String> failedCommits = newArrayList(); Thread[] threads = new Thread[10]; for (int k = 0; k < threads.length; k++) { final int threadId = k; threads[k] = new Thread(new Runnable() { @Override public void run() { for (int j = 0; run.get(); j++) { String nodeName = "b-" + threadId + "," + j; try { NodeBuilder root = nodeStore.getRoot().builder(); root.setChildNode(nodeName); nodeStore.merge(root, EmptyHook.INSTANCE, CommitInfo.EMPTY); Thread.sleep(5); } catch (CommitFailedException e) { failedCommits.add(nodeName); } catch (InterruptedException e) { Thread.interrupted(); break; } } } }); threads[k].start(); } store.compact(); run.set(false); for (Thread t : threads) { t.join(); } store.flush(); assumeTrue("Failed to acquire compaction lock", compactionSuccess.get()); assertTrue("Failed commits: " + failedCommits, failedCommits.isEmpty()); Set<UUID> afterSegments = new HashSet<UUID>(); collectSegments(store.getHead(), afterSegments); try { for (UUID u : beforeSegments) { assertFalse("Mixed segments found: " + u, afterSegments.contains(u)); } } finally { store.close(); } }
From source file:net.minecraftforge.gradle.util.ZipFileTree.java
public void visit(FileVisitor visitor) { if (!zipFile.exists()) { DeprecationLogger.nagUserOfDeprecatedBehaviour(String.format( "The specified zip file %s does not exist and will be silently ignored", getDisplayName())); return;/* w ww . ja va2 s.c o m*/ } if (!zipFile.isFile()) { throw new InvalidUserDataException( String.format("Cannot expand %s as it is not a file.", getDisplayName())); } AtomicBoolean stopFlag = new AtomicBoolean(); try { ZipFile zip = new ZipFile(zipFile); try { // The iteration order of zip.getEntries() is based on the hash of the zip entry. This isn't much use // to us. So, collect the entries in a map and iterate over them in alphabetical order. Map<String, ZipEntry> entriesByName = new TreeMap<String, ZipEntry>(); Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); entriesByName.put(entry.getName(), entry); } Iterator<ZipEntry> sortedEntries = entriesByName.values().iterator(); while (!stopFlag.get() && sortedEntries.hasNext()) { ZipEntry entry = sortedEntries.next(); if (entry.isDirectory()) { visitor.visitDir(new DetailsImpl(entry, zip, stopFlag)); } else { visitor.visitFile(new DetailsImpl(entry, zip, stopFlag)); } } } finally { zip.close(); } } catch (Exception e) { throw new GradleException(String.format("Could not expand %s.", getDisplayName()), e); } }
From source file:com.streamsets.pipeline.stage.origin.jdbc.AbstractTableJdbcSource.java
private synchronized boolean shutdownExecutorIfNeeded() { AtomicBoolean interrupted = new AtomicBoolean(false); Optional.ofNullable(executorService).ifPresent(executor -> { if (!executor.isTerminated()) { LOG.info("Shutting down executor service"); executor.shutdown();/*from w w w . j a va 2 s .com*/ try { executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { LOG.warn("Shutdown interrupted"); interrupted.set(true); } } }); return interrupted.get(); }