AtomicBoolean is a wrapping class that has a boolean data type. The AtomicBoolean 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
AtomicBoolean can guarantee concurrency at a lower cost than synchronized .
Let`s see how to use AtomicBoolean.
create object
AtomicBoolean can be created like this: The initial value is false, and if you want to change the initial value, you can pass a boolean object as an argument.
import java.util.concurrent.atomic.AtomicBoolean;
AtomicBoolean atomicBoolean = new AtomicBoolean();
System.out.println("value : " + atomicBoolean.get());
AtomicBoolean atomicBoolean2 = new AtomicBoolean(true);
System.out.println("value : " + atomicBoolean2.get());
// texture
// value : false
// value : true
get(), set(), getAndSet()
You must use the set(boolean)
method to change the boolean value of AtomicBoolean, and the get()
method to read the value.
AtomicBoolean atomicBoolean = new AtomicBoolean();
System.out.println("value : " + atomicBoolean.get());
atomicBoolean.set(true);
System.out.println("value : " + atomicBoolean.get());
// texture
// value : false
// value : true
getAndSet(boolean)
returns the current value and updates it with the value passed as an argument.
In the example below, the return value of getAndSet(true)
is false, but if you check it again after calling it, it is set to true.
AtomicBoolean atomicBoolean = new AtomicBoolean(false);
System.out.println("value(before setting) : " + atomicBoolean.getAndSet(true));
System.out.println("value(after setting) : " + atomicBoolean.get());
// texture
// value(before setting) : false
// value(after setting) : true
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.
Here is the compareAndSet( ) method`s API description.
/**
* 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 true if successful. False return indicates that
* the actual value was not equal to the expected value.
*/
public final boolean compareAndSet(boolean expect, boolean update)
Here is an example using compareAndSet(). The data is updated only when it matches the current value and true is returned.
boolean expected = true;
AtomicBoolean atomicBoolean = new AtomicBoolean(false);
System.out.println("success ? " + atomicBoolean.compareAndSet(expected, true));
System.out.println("value : " + atomicBoolean.get());
atomicBoolean.set(true);
System.out.println("success ? " + atomicBoolean.compareAndSet(expected, true));
System.out.println("value : " + atomicBoolean.get());
// texture
// success ? false
// value : false
// success ? true
// value : true
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)