BAEL-5682 - Atomic vs Volatile (#12528)

Co-authored-by: eugene.kovko <eugene.kovko@tensquaregames.com>
This commit is contained in:
Eugene Kovko 2022-08-02 03:16:24 +02:00 committed by GitHub
parent b58a7a7c12
commit 614795051e
4 changed files with 69 additions and 0 deletions

View File

@ -0,0 +1,16 @@
package com.baeldung.atomicvsvolatile;
import java.util.concurrent.atomic.AtomicInteger;
public class SafeAtomicCounter {
private final AtomicInteger counter = new AtomicInteger(0);
public int getValue() {
return counter.get();
}
public void increment() {
counter.incrementAndGet();
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.atomicvsvolatile;
public class UnsafeCounter {
private int counter;
public int getValue() {
return counter;
}
public void increment() {
counter++;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.atomicvsvolatile;
public class UnsafeVolatileCounter {
private volatile int counter;
public int getValue() {
return counter;
}
public void increment() {
counter++;
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.atomicvsvolatile;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.junit.Test;
public class SafeAtomicCounterUnitTest {
private static final int INCREMENT_COUNTER = 1000;
private static final int TIMEOUT = 100;
private static final int POOL_SIZE = 3;
@Test
public void givenMultiThread_whenSafeAtomicCounterIncrement() throws InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(POOL_SIZE);
SafeAtomicCounter safeCounter = new SafeAtomicCounter();
IntStream.range(0, INCREMENT_COUNTER).forEach(count -> service.submit(safeCounter::increment));
service.awaitTermination(TIMEOUT, TimeUnit.MILLISECONDS);
assertEquals(INCREMENT_COUNTER, safeCounter.getValue());
}
}