When multiple threads need to check and change the boolean. For example:
if (!initialized) {
initialize();
initialized = true;
}
This is not thread-safe. You can fix it by using AtomicBoolean
:
if (atomicInitialized.compareAndSet(false, true)) {
initialize();
}
More Related Contents:
- Why must wait() always be in synchronized block
- How to share data with two(2) SwingWorker class in Java
- ConcurrentModificationException despite using synchronized
- Volatile vs Static in Java
- Swing – Update Label
- How to make ThreadPoolExecutor’s submit() method block if it is saturated?
- When would you call java’s thread.run() instead of thread.start()?
- Convert from List to CompletableFuture
- Why there is no ConcurrentHashSet against ConcurrentHashMap
- What are the main uses of yield(), and how does it differ from join() and interrupt()?
- Volatile variable in Java
- What is the difference between synchronized on lockObject and using this as the lock?
- Why does Thread.isInterrupted () always return false?
- When should I use a CompletionService over an ExecutorService?
- Java memory model – can someone explain it?
- Are non-synchronised static methods thread safe if they don’t modify static class variables?
- Java concurrency: Countdown latch vs Cyclic barrier
- How to interrupt a BlockingQueue which is blocking on take()?
- Hashmap concurrency issue
- Which concurrent Queue implementation should I use in Java?
- Why should I use concurrent characteristic in parallel stream with collect?
- Java concurrency: is final field (initialized in constructor) thread-safe?
- Jboss Java EE container and an ExecutorService
- Why doesn’t volatile in java 5+ ensure visibility from another thread?
- Java: is there no AtomicFloat or AtomicDouble?
- How to pause/resume all threads in an ExecutorService in Java?
- Multithreading Socket communication Client/Server
- Not thread-safe Object publishing
- notifyAll() throws IllegalMonitorStateException
- Will a chain of method calls (CompletableFuture API) execute asynchronously if the first method in a chain is asynchronous?