AtomicLong vs Long
Rédigé par gorki Aucun commentaireProblem :
I searched for an simple example of AtomicLong vs Long problem.
Thanks to Ecosia IA (ChatGPT), here is a simple example
Solution :
Result is :
- Counter value (Long): 34938
- Counter value (AtomicLong): 100000
Here is the code :
package tools;
import java.util.concurrent.atomic.AtomicLong;
public class AtomicLongExample {
private static Long counter = 0L;
private static AtomicLong atomicCounter = new AtomicLong(0);
public static void main(String[] args) {
// Create and start multiple threads
Thread[] threads = new Thread[100];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(new CounterRunnable());
threads[i].start();
}
// Wait for all threads to finish
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Counter value (Long): " + counter);
System.out.println("Counter value (AtomicLong): " + atomicCounter.get());
}
static class CounterRunnable implements Runnable {
@Override
public void run() {
// Increment the counter using Long variable within a loop
// This may lead to race conditions and incorrect results
for (int i = 0; i < 1000; i++) {
counter++;
}
// Increment the counter using AtomicLong within a loop
// This ensures atomicity and thread-safety
for (int i = 0; i < 1000; i++) {
atomicCounter.incrementAndGet();
}
}
}
}