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.
AtomicInteger is slower than synchronized.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With