List of usage examples for java.util.concurrent.atomic AtomicInteger decrementAndGet
public final int decrementAndGet()
From source file:com.vmware.photon.controller.deployer.dcp.task.WaitForServiceTaskService.java
private void scheduleHealthCheckQuery(final State currentState, final HealthChecker healthChecker, final AtomicInteger retryCounter) { final Service service = this; Runnable runnable = new Runnable() { @Override/*from ww w .jav a 2 s .c o m*/ public void run() { if (retryCounter.decrementAndGet() < 0) { String errMessage = String.format("%s not ready after %s retries", currentState.containerType, currentState.maxRetries); ServiceUtils.logSevere(service, errMessage); failTask(new RuntimeException(errMessage)); return; } ServiceUtils.logInfo(service, "HealthCheck (%s) retry: %s of maxRetries(%s)", currentState.containerType, currentState.maxRetries - retryCounter.get(), currentState.maxRetries); if (healthChecker.isReady()) { sendStageProgressPatch(TaskState.TaskStage.FINISHED); return; } scheduleHealthCheckQuery(currentState, healthChecker, retryCounter); } }; getHost().schedule(runnable, currentState.taskPollDelay, TimeUnit.MILLISECONDS); }
From source file:org.axonframework.saga.SagaManagerTest.java
@Test public synchronized void testAccessToSagaWhileInCreation() throws InterruptedException { when(mockSagaFactory.createSaga(isA(Class.class))).thenReturn(mockSaga1); reset(mockSagaRepository);/* w w w. jav a2s.c om*/ when(mockSagaRepository.find(isA(Class.class), isA(AssociationValue.class))) .thenReturn(Collections.<String>emptySet()).thenReturn(singleton("saga1")); sagaCreationPolicy = SagaCreationPolicy.IF_NONE_FOUND; final AtomicInteger nestingCounter = new AtomicInteger(20); final EventMessage event = GenericEventMessage.asEventMessage(new Object()); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { if (nestingCounter.decrementAndGet() > 0) { UnitOfWork uow = DefaultUnitOfWork.startAndGet(); try { testSubject.handle(event); } finally { uow.commit(); } } return null; } }).when(mockSaga1).handle(isA(EventMessage.class)); testSubject.handle(event); verify(mockSagaRepository).add(mockSaga1); verify(mockSagaRepository, times(19)).commit(mockSaga1); verify(mockSagaRepository, never()).load("saga1"); }
From source file:org.apache.hadoop.raid.RaidHistogram.java
public synchronized void filterStalePoints(long endTime) throws IOException { int last = windowNum - 1; long windowTime = windows.get(last); NavigableSet<Point> windowSet = points.headSet(new Point(0, "", endTime - windowTime, null)); Iterator<Point> windowIterator = windowSet.iterator(); while (windowIterator.hasNext()) { Point p = windowIterator.next(); if (p.value == RECOVERY_FAIL) { AtomicInteger ca = failedRecoveredFiles.get(p.path); if (ca == null) { throw new IOException(p.path + " doesn't have counter in failedRecoveredFiles"); }/* www .ja va 2 s.c o m*/ if (ca.decrementAndGet() == 0) { totalFailedPaths.decrementAndGet(last); failedRecoveredFiles.remove(p.path); } } else { CounterArray ca = histo.get(p.value); if (ca == null) { throw new IOException(p.value + " doesn't have counter in histo"); } if (ca.decrementAndGet(last) == 0) { histo.remove(p.value); } totalPoints.decrementAndGet(last); } points.remove(p); } }
From source file:org.apache.hadoop.hbase.client.SimpleRequestController.java
@Override public void decTaskCounters(Collection<byte[]> regions, ServerName sn) { regions.forEach(regBytes -> {//from ww w. jav a 2s . co m AtomicInteger regionCnt = taskCounterPerRegion.get(regBytes); regionCnt.decrementAndGet(); }); taskCounterPerServer.get(sn).decrementAndGet(); tasksInProgress.decrementAndGet(); synchronized (tasksInProgress) { tasksInProgress.notifyAll(); } }
From source file:org.schedulesdirect.api.ZipEpgClient.java
@Override public void close() throws IOException { if (!closed) { purgeCache();/* w w w . j a v a 2 s . c o m*/ String vfsKey = getSrcZipKey(src); AtomicInteger i = CLNT_COUNT.get(vfsKey); int v = i != null ? i.decrementAndGet() : 0; if (v <= 0) { LOG.debug("Calling close() for " + vfsKey); vfs.close(); } else if (LOG.isDebugEnabled()) LOG.debug(String.format("Skipped close() for %s; c=%d", vfsKey, i != null ? i.get() : Integer.MIN_VALUE)); closed = true; } }
From source file:io.codis.nedis.codis.RoundRobinNedisClientPool.java
@Override public Future<Void> close() { if (!closed.compareAndSet(false, true)) { return closePromise; }/*from ww w . j av a 2 s . c o m*/ new Thread(getClass().getSimpleName() + "-Closer") { @Override public void run() { try { watcher.close(); } catch (IOException e) { LOG.warn("IOException should not have been thrown", e); } if (closeCurator) { curatorClient.close(); } synchronized (RoundRobinNedisClientPool.this) { List<PooledObject> toClose = pools; if (toClose.isEmpty()) { closePromise.trySuccess(null); return; } final AtomicInteger remaining = new AtomicInteger(toClose.size()); FutureListener<Void> listener = new FutureListener<Void>() { @Override public void operationComplete(Future<Void> future) throws Exception { if (remaining.decrementAndGet() == 0) { closePromise.trySuccess(null); } } }; for (PooledObject pool : toClose) { pool.pool.close().addListener(listener); } } } }.start(); return closePromise; }
From source file:org.springframework.amqp.rabbit.connection.AbstractConnectionFactoryTests.java
@Test public void testWithListener() throws Exception { com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock( com.rabbitmq.client.ConnectionFactory.class); com.rabbitmq.client.Connection mockConnection = mock(com.rabbitmq.client.Connection.class); when(mockConnectionFactory.newConnection(any(ExecutorService.class), anyString())) .thenReturn(mockConnection); final AtomicInteger called = new AtomicInteger(0); AbstractConnectionFactory connectionFactory = createConnectionFactory(mockConnectionFactory); connectionFactory.setConnectionListeners(Collections.singletonList(new ConnectionListener() { @Override/*from w ww . j ava 2 s . co m*/ public void onCreate(Connection connection) { called.incrementAndGet(); } @Override public void onClose(Connection connection) { called.decrementAndGet(); } })); Log logger = spy(TestUtils.getPropertyValue(connectionFactory, "logger", Log.class)); doReturn(true).when(logger).isInfoEnabled(); new DirectFieldAccessor(connectionFactory).setPropertyValue("logger", logger); Connection con = connectionFactory.createConnection(); assertEquals(1, called.get()); ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class); verify(logger).info(captor.capture()); assertThat(captor.getValue(), containsString("Created new connection: SimpleConnection")); con.close(); assertEquals(1, called.get()); verify(mockConnection, never()).close(anyInt()); connectionFactory.createConnection(); assertEquals(1, called.get()); connectionFactory.destroy(); assertEquals(0, called.get()); verify(mockConnection, atLeastOnce()).close(anyInt()); verify(mockConnectionFactory, times(1)).newConnection(any(ExecutorService.class), anyString()); }
From source file:org.waveprotocol.box.server.waveserver.RemoteWaveletContainerImpl.java
private void internalUpdate(final List<ByteString> deltas, final String domain, final WaveletFederationProvider federationProvider, final CertificateManager certificateManager, final SettableFuture<Void> futureResult) { // Turn raw serialised ByteStrings in to a more useful representation final List<ByteStringMessage<ProtocolAppliedWaveletDelta>> appliedDeltas = Lists.newArrayList(); for (ByteString delta : deltas) { try {/* w w w . jav a 2 s . c o m*/ appliedDeltas.add(ByteStringMessage.parseProtocolAppliedWaveletDelta(delta)); } catch (InvalidProtocolBufferException e) { LOG.info("Invalid applied delta protobuf for incoming " + getWaveletName(), e); acquireWriteLock(); try { markStateCorrupted(); } finally { releaseWriteLock(); } futureResult.setException(new FederationException( FederationErrors.badRequest("Invalid applied delta protocol buffer"))); return; } } LOG.info("Got update: " + appliedDeltas); // Fetch any signer info that we don't already have and then run internalUpdate final AtomicInteger numSignerInfoPrefetched = new AtomicInteger(1); // extra 1 for sentinel final Runnable countDown = new Runnable() { @Override public void run() { if (numSignerInfoPrefetched.decrementAndGet() == 0) { internalUpdateAfterSignerInfoRetrieval(appliedDeltas, domain, federationProvider, certificateManager, futureResult); } } }; SignerInfoPrefetchResultListener prefetchListener = new SignerInfoPrefetchResultListener() { @Override public void onFailure(FederationError error) { LOG.warning("Signer info prefetch failed: " + error); countDown.run(); } @Override public void onSuccess(ProtocolSignerInfo signerInfo) { LOG.info("Signer info prefetch success for " + signerInfo.getDomain()); countDown.run(); } }; for (ByteStringMessage<ProtocolAppliedWaveletDelta> appliedDelta : appliedDeltas) { ProtocolSignedDelta toVerify = appliedDelta.getMessage().getSignedOriginalDelta(); HashedVersion deltaEndVersion; try { deltaEndVersion = AppliedDeltaUtil.calculateResultingHashedVersion(appliedDelta); } catch (InvalidProtocolBufferException e) { LOG.warning("Skipping illformed applied delta " + appliedDelta, e); continue; } for (ProtocolSignature sig : toVerify.getSignatureList()) { if (certificateManager.retrieveSignerInfo(sig.getSignerId()) == null) { LOG.info("Fetching signer info " + Base64.encodeBase64(sig.getSignerId().toByteArray())); numSignerInfoPrefetched.incrementAndGet(); certificateManager.prefetchDeltaSignerInfo(federationProvider, sig.getSignerId(), getWaveletName(), deltaEndVersion, prefetchListener); } } } // If we didn't fetch any signer info, run internalUpdate immediately countDown.run(); }
From source file:org.apache.distributedlog.BKLogHandler.java
private void completeReadLogSegmentsFromStore(final Set<String> removedSegments, final Map<String, LogSegmentMetadata> addedSegments, final Comparator<LogSegmentMetadata> comparator, final CompletableFuture<Versioned<List<LogSegmentMetadata>>> readResult, final Version logSegmentNamesVersion, final AtomicInteger numChildren, final AtomicInteger numFailures) { if (0 != numChildren.decrementAndGet()) { return;//from w ww.java 2 s . c om } if (numFailures.get() > 0) { return; } // update the cache only when fetch completed and before #getCachedLogSegments updateLogSegmentCache(removedSegments, addedSegments); List<LogSegmentMetadata> segmentList; try { segmentList = getCachedLogSegments(comparator); } catch (UnexpectedException e) { readResult.completeExceptionally(e); return; } readResult.complete(new Versioned<List<LogSegmentMetadata>>(segmentList, logSegmentNamesVersion)); }
From source file:com.cloudera.oryx.app.als.FeatureVectorsTest.java
@Test public void testConcurrent() throws Exception { FeatureVectors fv = new FeatureVectors(); AtomicInteger counter = new AtomicInteger(); int numWorkers = 16; int numIterations = 10000; ExecUtils.doInParallel(numWorkers, i -> { for (int j = 0; j < numIterations; j++) { int c = counter.getAndIncrement(); fv.setVector(Integer.toString(c), new float[] { c }); }/*from w w w . j a va 2 s .c om*/ }); assertEquals((long) numIterations * numWorkers, fv.size()); assertEquals((long) numIterations * numWorkers, counter.get()); ExecUtils.doInParallel(numWorkers, i -> { for (int j = 0; j < numIterations; j++) { fv.removeVector(Integer.toString(counter.decrementAndGet())); } }); assertEquals(0, fv.size()); }