List of usage examples for java.util.concurrent.atomic AtomicInteger getAndDecrement
public final int getAndDecrement()
From source file:Main.java
public static void main(String[] argv) throws Exception { AtomicInteger atomicInteger = new AtomicInteger(); System.out.println(atomicInteger.getAndDecrement()); }
From source file:com.android.tools.swing.ui.NavigationComponent.java
private void updateText() { if (myItemStack.isEmpty()) { setText(""); return;//from w w w. j av a2 s. c o m } if (myItemStack.size() == 1 && hasRootItem && !myDisplaySingleRoot) { setText(""); return; } final AtomicInteger id = new AtomicInteger(myItemStack.size() - 1); String text = Joiner.on(" > ") .join(Iterators.transform(myItemStack.descendingIterator(), new Function<T, String>() { @Override public String apply(T input) { // Do not display link for the last element. if (id.get() == 0) { return input.getDisplayText(); } return String.format("<a href=\"%d\">%s</a>", id.getAndDecrement(), input.getDisplayText()); } @Override public boolean equals(Object object) { return false; } })); setText(text); }
From source file:com.googlecode.msidor.springframework.integration.channel.ConcurentOrderedMultiQueueChannel.java
/** * Handles the demands for messages/*from ww w . j a va 2s. c o m*/ * * @param timeout [ms] - time for which the thread will stay blocked if there are no eligible messages to process. * @return message to process */ @Override protected Message<?> doReceive(long timeout) { log.trace("Asking for message to process"); //the message to be returned Message<?> messageToReturn = null; int c = -1; long nanos = TimeUnit.MILLISECONDS.toNanos(timeout); final ReentrantLock lock = this.objectLock; final AtomicInteger count = this.count; try { //take the lock lock.lockInterruptibly(); while (messageToReturn == null) { //try to get eligible message messageToReturn = findEligibleMessage(); //if message was found if (messageToReturn != null) { //decrement the global messages counter c = count.getAndDecrement(); //if there are some messages wake up the next consumer thread to check if there is new eligible message if (c > 0) newMessagesToCheck.signal(); } else { //go to sleep waiting for new eligible message if (timeout <= 0) { newMessagesToCheck.await(); } else { nanos = newMessagesToCheck.awaitNanos(nanos); if (nanos <= 0) return null; } } } } catch (InterruptedException e) { log.trace("Lock interrupted by other thread"); } finally { //if message was found, wake the producer thread to notify it that there is a free space to insert new message if (messageToReturn != null) notFull.signal(); lock.unlock(); } log.trace("Rreceiving message " + messageToReturn); return messageToReturn; }
From source file:org.zodiark.service.action.ActionServiceImpl.java
/** * {@inheritDoc}//w w w . ja v a 2 s . com */ public void actionStarted(Envelope e) { try { final PublisherResults results = mapper.readValue(e.getMessage().getData(), PublisherResults.class); eventBus.message(RETRIEVE_PUBLISHER, results.getUuid(), new Reply<PublisherEndpoint, String>() { @Override public void ok(final PublisherEndpoint p) { final AtomicInteger time = new AtomicInteger(p.action().time()); final AtmosphereResource publisher = p.resource(); final AtmosphereResource subscriber = p.action().subscriber().resource(); final Future<?> timerFuture = timer.scheduleAtFixedRate(new Runnable() { @Override public void run() { if (time.get() == 0) return; Message m = new Message(); m.setPath(ACTION_TIMER); try { m.setData(mapper.writeValueAsString(time.getAndDecrement())); Envelope e = Envelope.newPublisherMessage(p.uuid(), m); String w = mapper.writeValueAsString(e); publisher.write(w); e = Envelope.newSubscriberMessage(p.uuid(), m); w = mapper.writeValueAsString(e); subscriber.write(w); } catch (JsonProcessingException e1) { logger.error("", e1); } } }, 1, 1, TimeUnit.SECONDS); timer.schedule(new Runnable() { @Override public void run() { timerFuture.cancel(false); Message m = new Message(); m.setPath(ACTION_COMPLETED); try { m.setData(mapper.writeValueAsString(new PublisherResults("OK"))); Envelope e = Envelope.newPublisherMessage(p.uuid(), m); String w = mapper.writeValueAsString(e); publisher.write(w); m.setData(mapper.writeValueAsString(new SubscriberResults("OK"))); e = Envelope.newSubscriberMessage(p.uuid(), m); w = mapper.writeValueAsString(e); subscriber.write(w); } catch (JsonProcessingException e1) { logger.error("", e1); } finally { eventBus.message(STREAMING_COMPLETE_ACTION, p); } } }, p.action().time(), TimeUnit.SECONDS); } @Override public void fail(ReplyException replyException) { logger.error("Unable to retrieve Publishere for {}", results.getUuid()); } }); } catch (IOException e1) { logger.error("", e1); } }
From source file:org.elasticsearch.client.sniff.SnifferTests.java
/** * Test multiple sniffing rounds by mocking the {@link Scheduler} as well as the {@link HostsSniffer}. * Simulates the ordinary behaviour of {@link Sniffer} when sniffing on failure is not enabled. * The {@link CountingHostsSniffer} doesn't make any network connection but may throw exception or return no hosts, which makes * it possible to verify that errors are properly handled and don't affect subsequent runs and their scheduling. * The {@link Scheduler} implementation submits rather than scheduling tasks, meaning that it doesn't respect the requested sniff * delays while allowing to assert that the requested delays for each requested run and the following one are the expected values. *//* ww w. j a v a2 s.c om*/ public void testOrdinarySniffRounds() throws Exception { final long sniffInterval = randomLongBetween(1, Long.MAX_VALUE); long sniffAfterFailureDelay = randomLongBetween(1, Long.MAX_VALUE); RestClient restClient = mock(RestClient.class); CountingHostsSniffer hostsSniffer = new CountingHostsSniffer(); final int iters = randomIntBetween(30, 100); final Set<Future<?>> futures = new CopyOnWriteArraySet<>(); final CountDownLatch completionLatch = new CountDownLatch(1); final AtomicInteger runs = new AtomicInteger(iters); final ExecutorService executor = Executors.newSingleThreadExecutor(); final AtomicReference<Future<?>> lastFuture = new AtomicReference<>(); final AtomicReference<Sniffer.Task> lastTask = new AtomicReference<>(); Scheduler scheduler = new Scheduler() { @Override public Future<?> schedule(Sniffer.Task task, long delayMillis) { assertEquals(sniffInterval, task.nextTaskDelay); int numberOfRuns = runs.getAndDecrement(); if (numberOfRuns == iters) { //the first call is to schedule the first sniff round from the Sniffer constructor, with delay O assertEquals(0L, delayMillis); assertEquals(sniffInterval, task.nextTaskDelay); } else { //all of the subsequent times "schedule" is called with delay set to the configured sniff interval assertEquals(sniffInterval, delayMillis); assertEquals(sniffInterval, task.nextTaskDelay); if (numberOfRuns == 0) { completionLatch.countDown(); return null; } } //we submit rather than scheduling to make the test quick and not depend on time Future<?> future = executor.submit(task); futures.add(future); if (numberOfRuns == 1) { lastFuture.set(future); lastTask.set(task); } return future; } @Override public void shutdown() { //the executor is closed externally, shutdown is tested separately } }; try { new Sniffer(restClient, hostsSniffer, scheduler, sniffInterval, sniffAfterFailureDelay); assertTrue("timeout waiting for sniffing rounds to be completed", completionLatch.await(1000, TimeUnit.MILLISECONDS)); assertEquals(iters, futures.size()); //the last future is the only one that may not be completed yet, as the count down happens //while scheduling the next round which is still part of the execution of the runnable itself. assertTrue(lastTask.get().hasStarted()); lastFuture.get().get(); for (Future<?> future : futures) { assertTrue(future.isDone()); future.get(); } } finally { executor.shutdown(); assertTrue(executor.awaitTermination(1000, TimeUnit.MILLISECONDS)); } int totalRuns = hostsSniffer.runs.get(); assertEquals(iters, totalRuns); int setHostsRuns = totalRuns - hostsSniffer.failures.get() - hostsSniffer.emptyList.get(); verify(restClient, times(setHostsRuns)).setHosts(Matchers.<HttpHost>anyVararg()); verifyNoMoreInteractions(restClient); }
From source file:org.apache.synapse.transport.nhttp.ClientHandler.java
/** * Remove a connection record for this host:port pair from active connections records. * * @param inetConnection connection that need to be removed from the active connections records *//* ww w.j a v a2 s .c o m*/ private void removeConnectionRecord(HttpInetConnection inetConnection) { AtomicInteger connections = openConnections .get(inetConnection.getRemoteAddress().getHostName() + ":" + inetConnection.getRemotePort()); if (connections == null) { connections = openConnections .get(inetConnection.getRemoteAddress().getHostAddress() + ":" + inetConnection.getRemotePort()); } if (connections != null) { int no = connections.getAndDecrement(); lock.lock(); try { if (no == 0) { if (null == openConnections.remove(inetConnection.getRemoteAddress().getHostName() + ":" + inetConnection.getRemotePort())) { } else { openConnections.remove(inetConnection.getRemoteAddress().getHostAddress() + ":" + inetConnection.getRemotePort()); } } } finally { lock.unlock(); } } }
From source file:org.apache.nifi.processors.standard.util.TestJdbcCommon.java
@Test public void testConvertToAvroStreamForBigDecimal() throws SQLException, IOException { final ResultSetMetaData metadata = mock(ResultSetMetaData.class); when(metadata.getColumnCount()).thenReturn(1); when(metadata.getColumnType(1)).thenReturn(Types.NUMERIC); when(metadata.getColumnName(1)).thenReturn("The.Chairman"); when(metadata.getTableName(1)).thenReturn("1the::table"); final ResultSet rs = mock(ResultSet.class); when(rs.getMetaData()).thenReturn(metadata); final AtomicInteger counter = new AtomicInteger(1); Mockito.doAnswer(new Answer<Boolean>() { @Override//ww w. java2s . c o m public Boolean answer(InvocationOnMock invocation) throws Throwable { return counter.getAndDecrement() > 0; } }).when(rs).next(); final BigDecimal bigDecimal = new BigDecimal(38D); when(rs.getObject(Mockito.anyInt())).thenReturn(bigDecimal); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); JdbcCommon.convertToAvroStream(rs, baos, true); final byte[] serializedBytes = baos.toByteArray(); final InputStream instream = new ByteArrayInputStream(serializedBytes); final DatumReader<GenericRecord> datumReader = new GenericDatumReader<>(); try (final DataFileStream<GenericRecord> dataFileReader = new DataFileStream<>(instream, datumReader)) { GenericRecord record = null; while (dataFileReader.hasNext()) { record = dataFileReader.next(record); assertEquals("_1the__table", record.getSchema().getName()); assertEquals(bigDecimal.toString(), record.get("The_Chairman").toString()); } } }
From source file:org.apache.nifi.processors.standard.util.TestJdbcCommon.java
@Test public void testConvertToAvroStreamForShort() throws SQLException, IOException { final ResultSetMetaData metadata = mock(ResultSetMetaData.class); when(metadata.getColumnCount()).thenReturn(1); when(metadata.getColumnType(1)).thenReturn(Types.TINYINT); when(metadata.getColumnName(1)).thenReturn("t_int"); when(metadata.getTableName(1)).thenReturn("table"); final ResultSet rs = mock(ResultSet.class); when(rs.getMetaData()).thenReturn(metadata); final AtomicInteger counter = new AtomicInteger(1); Mockito.doAnswer(new Answer<Boolean>() { @Override//from w w w . j a va 2 s.c om public Boolean answer(InvocationOnMock invocation) throws Throwable { return counter.getAndDecrement() > 0; } }).when(rs).next(); final short s = 25; when(rs.getObject(Mockito.anyInt())).thenReturn(s); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); JdbcCommon.convertToAvroStream(rs, baos, false); final byte[] serializedBytes = baos.toByteArray(); final InputStream instream = new ByteArrayInputStream(serializedBytes); final DatumReader<GenericRecord> datumReader = new GenericDatumReader<>(); try (final DataFileStream<GenericRecord> dataFileReader = new DataFileStream<>(instream, datumReader)) { GenericRecord record = null; while (dataFileReader.hasNext()) { record = dataFileReader.next(record); assertEquals(Short.toString(s), record.get("t_int").toString()); } } }
From source file:org.codice.ddf.admin.application.service.migratable.ProfileMigratableTest.java
private static Answer succeedsImportAndStopRecordingTasksAtAttempt(AtomicInteger attempts, int attempt) { return AdditionalAnswers.<Boolean, ProfileMigrationReport, JsonProfile>answer((r, p) -> { if (attempts.getAndDecrement() > attempt) { r.recordTask();// w w w .ja v a 2 s . co m } return true; }); }
From source file:org.neo4j.io.pagecache.impl.SingleFilePageSwapperTest.java
@Test public void mustCloseFilesIfTakingFileLockThrows() throws Exception { assumeFalse("No file locking on Windows", SystemUtils.IS_OS_WINDOWS); // no file locking on Windows. final AtomicInteger openFilesCounter = new AtomicInteger(); PageSwapperFactory factory = swapperFactory(); DefaultFileSystemAbstraction fs = new DefaultFileSystemAbstraction(); factory.setFileSystemAbstraction(new DelegatingFileSystemAbstraction(fs) { @Override//from w ww .j av a 2s . c om public StoreChannel open(File fileName, String mode) throws IOException { openFilesCounter.getAndIncrement(); return new DelegatingStoreChannel(super.open(fileName, mode)) { @Override public void close() throws IOException { openFilesCounter.getAndDecrement(); super.close(); } }; } }); File file = testDir.file("file"); try (StoreChannel ch = fs.create(file); FileLock lock = ch.tryLock()) { createSwapper(factory, file, 4, NO_CALLBACK, false).close(); fail("Creating a page swapper for a locked channel should have thrown"); } catch (FileLockException e) { // As expected. } assertThat(openFilesCounter.get(), is(0)); }