Junior — Middle
What are the easiest methods you can use to ensure data consistency between threads?
sobes.tech AI
Answer from AI
To ensure data consistency between threads in Java, several simple methods can be used:
- The
volatilekeyword — guarantees that changes to a variable are immediately visible to all threads, without caching. - Synchronized blocks (
synchronized) — provide mutual exclusion when accessing shared resources. - Using atomic classes from
java.util.concurrent.atomic— for example,AtomicInteger, which provide atomic operations without locks.
Example with volatile:
volatile boolean flag = false;
// Thread 1
flag = true;
// Thread 2
if (flag) {
// will see the updated value
}
These methods are simple and effective for basic synchronization and data consistency.