What is Thread Safety in Java: Explanation and Examples
thread safety means that a piece of code or data can be safely used by multiple threads at the same time without causing errors or unexpected behavior. It ensures that shared resources are accessed in a way that prevents conflicts or data corruption.How It Works
Imagine you have a shared notebook that many friends want to write in at the same time. If everyone writes without any order, the notes will get mixed up and confusing. Thread safety in Java works like a rule that lets only one friend write at a time or organizes the writing so that the notebook stays neat and correct.
In programming, threads are like these friends, and the shared notebook is data or resources used by the program. Java provides tools like synchronized blocks or locks to control access, making sure only one thread changes the data at a time or that changes happen in a safe order. This prevents problems like two threads changing the same data simultaneously and causing errors.
Example
This example shows a simple counter that multiple threads try to increase. Without thread safety, the final count might be wrong because threads interfere. Using synchronized ensures the count is correct.
public class Counter { private int count = 0; public synchronized void increment() { count++; } public int getCount() { return count; } public static void main(String[] args) throws InterruptedException { Counter counter = new Counter(); Thread t1 = new Thread(() -> { for (int i = 0; i < 1000; i++) { counter.increment(); } }); Thread t2 = new Thread(() -> { for (int i = 0; i < 1000; i++) { counter.increment(); } }); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("Final count: " + counter.getCount()); } }
When to Use
Use thread safety when your Java program has multiple threads working with the same data or resources. This is common in apps that do many things at once, like web servers, games, or apps that handle user input and background tasks simultaneously.
Without thread safety, your program might crash, show wrong results, or behave unpredictably. Ensuring thread safety helps keep your program reliable and correct when many threads run together.
Key Points
- Thread safety prevents errors when multiple threads access shared data.
- Java uses
synchronizedand locks to control thread access. - Not all code needs to be thread-safe; only shared mutable data requires it.
- Proper thread safety improves program reliability and correctness.