AtomicInteger is a wrapping class that has an int data type. The AtomicInteger class guarantees concurrency in a multithreaded environment.
There are 3 ways to solve concurrency problem in Java.
- "volatile" guarantees concurrency only when writing from Thread1 and reading from Thread2. This can be a problem if you write in two threads.
- By using "synchronized" you can safely guarantee concurrency. but the most expensive
- Atomic classes use compare-and-swap to ensure concurrency. There is no problem with writing data from multiple threads
AtomicInteger can guarantee concurrency at a lower cost than synchronized .
Let`s see how to use AtomicInteger.
create object
AtomicInteger can be created like this: The initial value is 0, and if you want to change the initial value, you can pass an int variable as an argument.
public void atomicInteger1() {
AtomicInteger atomic = new AtomicInteger();
System.out.println("value : " + atomic.get());
AtomicInteger atomic2 = new AtomicInteger(10);
System.out.println("value : " + atomic2.get());
}
result
value : 0
value : 10
get(), set(), getAndSet()
You must use the set(int)
method to change the int value of AtomicInteger, and the get()
method to read the value.
public void atomicInteger2() {
AtomicInteger atomic = new AtomicInteger();
System.out.println("value : " + atomic.get());
atomic.set(100);
System.out.println("value : " + atomic.get());
}
result
value : 0
value : 100
getAndSet(int)
returns the current value and updates it with the value passed as an argument.
public void atomicInteger3() {
AtomicInteger atomic = new AtomicInteger(10);
System.out.println("value(before setting) : " + atomic.getAndSet(20));
System.out.println("value(after setting) : " + atomic.get());
}
result
value(before setting) : 10
value(after setting) : 20
compareAndSet()
compareAndSet(expect, update) returns true if the current value is the same as the expected value (expect). Otherwise, there is no data change and returns false.
/**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
*
* @param expect the expected value
* @param update the new value
* @return {@code true} if successful. False return indicates that
* the actual value was not equal to the expected value.
*/
public final boolean compareAndSet(int expect, int update)
Here is an example using compareAndSet(). The data is updated only when it matches the current value and true is returned.
public void atomicInteger4() {
int expected = 20;
AtomicInteger atomic = new AtomicInteger(10);
System.out.println("success ? " + atomic.compareAndSet(expected, 100));
System.out.println("value : " + atomic.get());
atomic.set(20);
System.out.println("success ? " + atomic.compareAndSet(expected, 100));
System.out.println("value : " + atomic.get());
}
result
success ? false
value : 10
success ? true
value : 100
Reference
Related Posts
- Java - Remove items from List while iterating
- Java - How to find key by value in HashMap
- Java - Update the value of a key in HashMap
- Java - How to put quotes in a string
- Java - How to put a comma (,) after every 3 digits
- BiConsumer example in Java 8
- Java 8 - Consumer example
- Java 8 - BinaryOperator example
- Java 8 - BiPredicate Example
- Java 8 - Predicate example
- Java 8 - Convert Stream to List
- Java 8 - BiFunction example
- Java 8 - Function example
- Java - Convert List to Map
- Exception testing in JUnit
- Hamcrest Collections Matcher
- Hamcrest equalTo () Matcher
- AAA pattern of unit test (Arrange/Act/Assert)
- Hamcrest Text Matcher
- Hamcrest Custom Matcher
- Why Junit uses Hamcrest
- Java - ForkJoinPool
- Java - How to use Futures
- Java - Simple HashTable implementation
- Java - Create a file in a specific path
- Java - Mockito의 @Mock, @Spy, @Captor, @InjectMocks
- Java - How to write test code using Mockito
- Java - Synchronized block
- Java - How to decompile a ".class" file into a Java file (jd-cli decompiler)
- Java - How to generate a random number
- Java - Calculate powers, Math.pow()
- Java - Calculate the square root, Math.sqrt()
- Java - How to compare String (==, equals, compare)
- Java - Calculate String Length
- Java - case conversion & comparison insensitive (toUpperCase, toLowerCase, equalsIgnoreCase)