![]() |
VOOZH | about |
Thread Safety means when multiple threads access the same object or piece of code at the same time, the program still behaves correctly, without data corruption or unexpected results.
There are four ways to achieve Thread Safety in Java. These are:
We use the synchronized keyword to ensure only one thread can access a method or block of code at a time. It helps in preventing race conditions.
Thread A : 11 Thread A : 12 Thread A : 13 Thread A : 14 Thread A : 15 Thread B : 11 Thread B : 12 Thread B : 13 Thread B : 14 Thread B : 15
Explanation: The synchronized keyword ensures that only one thread executes the sum() method at a time by locking the object’s monitor. While one thread holds the lock, other threads must wait until it is released, after which they can proceed.
Volatile Keyword ensures visibility of variable changes across threads. It does not guarantee atomicity, but ensures every thread reads the latest value from main memory, not cache.
a=5 b=5 a=5 b=5 a=5 b=5 a=5 b=5 a=5 b=5
Explanation: The volatile keyword ensures that variables are always read from main memory, so changes made by one thread are immediately visible to others. As a result, when one thread updates the values, other threads see the updated values instantly.
Using an atomic variable is another way to achieve thread-safety in java. When variables are shared by multiple threads, the atomic variable ensures that threads don't crash into each other.
4000
Explanation: AtomicInteger uses compare-and-swap (CAS) to perform operations atomically without explicit synchronization. As a result, incrementAndGet() safely updates the shared counter, allowing multiple threads to modify it without conflicts.
Immutable objects are inherently thread-safe, as their state cannot change after creation. Mark fields as final and don’t provide setters.
Explanation: The class is made immutable by declaring it final, using final fields, and not providing setters. This ensures the object’s state cannot change, making it safe for use across multiple threads.
Features | Thread-Safe | Non-Thread Safe |
|---|---|---|
Definition | It is used to handle concurrent access by multiple threads safely | Not designed for safe concurrent access by multiple threads |
Synchronization | Uses synchronization internally for Thread safety | It does not use synchronization; access must be manually managed. |
Use Case | It is used in multi-threaded environments. | It is mainly used for single-threaded scenarios or with external sync. |
Performance | Slower due to synchronization overhead. | Faster, as there’s no locking mechanism. |
| May not scale well under high concurrency due to lock contention | Scales well if used in a controlled single-threaded context |
Examples | Vector, Hashtable, ConcurrentHashMap, StringBuffer | ArrayList, HashMap, StringBuilder, SimpleDateFormat |