Visibility and atomicity are two different concepts in multithreaded programming. Visibility ensures that changes made by one thread are immediately visible to other threads, while atomicity ensures that an operation is executed as a single, indivisible unit without interference from other threads. Both are essential for writing correct and thread-safe concurrent applications.
Key Points: • Visibility deals with sharing the latest value of a variable across threads and is commonly achieved using the volatile keyword or synchronization. • Atomicity guarantees that an operation completes entirely or not at all, preventing partial updates caused by thread interference. • A variable can be visible without being atomic; for example, volatile ensures visibility but does not make compound operations like count++ atomic.
Example: If Thread A updates a shared flag variable and Thread B needs to see the updated value immediately, visibility is required. If multiple threads increment a shared counter, atomicity is required to prevent lost updates.
Code Example:
import java.util.concurrent.atomic.AtomicInteger;
public class CounterDemo {
private volatile boolean flag = true; // Visibility
private AtomicInteger count =
new AtomicInteger(0); // Atomicity
public void increment() {
count.incrementAndGet();
}
}Interview Tip: A concise interview answer is: Visibility ensures that changes made by one thread are visible to other threads, while atomicity ensures that an operation executes as a single uninterrupted unit. The volatile keyword provides visibility, whereas synchronized blocks, locks, or atomic classes provide atomicity.