Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to wait for the change on an atomic integer

Is there a way to wait on an AtomicInteger so that I don't have to keep sleeping my current thread and keep checking on the AtomicInteger like this

while(atomicInt.get() >= 0) {
    Thread.sleep(1000)
}

I know there is such a thing as a CountDownLatch but that only allows me to decrement I also need it to be able to increment

Further BackStory - I have a loop creating threads and I need to wait on one of the threads execution to finish before creating a new thread. I however am using an Executors.newFixedThreadPool(numThreads) and the only way to wait on it seems to be to call the shutdown method await termination and then create a new threadPool so instead I was using an atomic integer to keep track of how many threads were running and/or on the queue so that when that number decreased I could continue with the loop.

like image 912
jgerstle Avatar asked May 08 '12 14:05

jgerstle


People also ask

Are atomic integers slow?

AtomicInteger is slower than synchronized.

How do you increment an atomic Integer?

incrementAndGet() – Atomically increments the current value by 1 and returns new value after the increment. It is equivalent to ++i operation. getAndIncrement() – Atomically increment the current value and returns old value. It is equivalent to i++ operation.

How do you define an atomic Integer?

An AtomicInteger is used in applications such as atomically incremented counters, and cannot be used as a replacement for an Integer . However, this class does extend Number to allow uniform access by tools and utilities that deal with numerically-based classes.

Why do we need atomic integers?

AtomicInteger class provides operations on underlying int value that can be read and written atomically, and also contains advanced atomic operations. AtomicInteger supports atomic operations on underlying int variable. It have get and set methods that work like reads and writes on volatile variables.


1 Answers

I think a closer match to what you want is a Phaser. My rough understanding is that its a bit like an incrementing counter where you can block until the number is incremented.

// This constructor one party (so it expects one advance per phase).
Phaser phaser = new Phaser(1);
try {
  // This will timeout as phase 0 hasn't arrived yet.
  phaser.awaitAdvanceInterruptibly(0, 1, TimeUnit.MILLISECONDS);
  fail();
}
catch (TimeoutException expected) {
}

// Arrive phase 0
phaser.arrive();
phaser.awaitAdvance(0);
try {
  // Phase 1 will timeout..
  phaser.awaitAdvanceInterruptibly(1, 1, TimeUnit.MILLISECONDS);
  fail();
}
catch (TimeoutException expected) {
}

// Arrive phase 1
phaser.arrive();
phaser.awaitAdvance(0);
phaser.awaitAdvance(1);
like image 130
Mumrah Avatar answered Oct 06 '22 23:10

Mumrah