-
Atomic VariablesStaticPL/JAVA 2020. 2. 26. 12:34
1. Overview
A small toolkit of classes that support lock-free thread-safe programming on single variables. In essence, the classes in this package extend the notion of volatile values, fields, and array elements to those that also provide an atomic conditional update operation of the form
2. Example
public class demo { public static void main(String[] args) throws InterruptedException { InventoryCounter inventoryCounter = new InventoryCounter(); DecrementingThread decrementingThread = new DecrementingThread(inventoryCounter); IncrementingThread incrementingThread = new IncrementingThread(inventoryCounter); decrementingThread.start(); incrementingThread.start(); decrementingThread.join(); incrementingThread.join(); System.out.println(inventoryCounter.getItems()); } public static class DecrementingThread extends Thread { private InventoryCounter inventoryCounter; public DecrementingThread(InventoryCounter inventoryCounter) { this.inventoryCounter = inventoryCounter; } @Override public void run() { for (int i = 0; i < 10000; i++) { inventoryCounter.decrement(); } } } public static class IncrementingThread extends Thread { private InventoryCounter inventoryCounter; public IncrementingThread(InventoryCounter inventoryCounter) { this.inventoryCounter = inventoryCounter; } @Override public void run() { for (int i = 0; i < 10000; i++) { inventoryCounter.increment(); } } } //Thread unsafe approach // public static class InventoryCounter { // private int items = 0; // public void increment() { items++; } // public void decrement() { items--; } // public int getItems() { return items; } // } // Thread safe approach using atomic variable public static class InventoryCounter { private AtomicInteger item = new AtomicInteger(0); public void increment() { item.incrementAndGet(); } public void decrement() { item.decrementAndGet(); } public int getItems() { return item.get(); } } }
4. Reference
https://docs.oracle.com/javase/tutorial/essential/concurrency/atomicvars.html
https://www.baeldung.com/java-atomic-variables
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/package-summary.html
https://dzone.com/articles/java-concurrency-atomic-variables
'StaticPL > JAVA' 카테고리의 다른 글
ReentrantLock, lockInterruptibly, and tryLock (0) 2020.02.27 synchronized (0) 2020.02.27 Access Modifier (0) 2020.02.23 Is-A and Has-A Relationship in Java (0) 2020.02.05 Boxing, unboxing, and autoboxing (0) 2019.09.27