Thread Safety and how to achieve it in Java
As we know Java has a feature, Multithreading, which is a process of running multiple threads simultaneously. When multiple threads are working on the same data, and the value of our data is changing, that scenario is not thread-safe and we will get inconsistent results. When a thread is already working on an object and preventing another thread on working on the same object, this process is called Thread-Safety.
How to achieve Thread Safety
There are four ways to achieve Thread Safety in Java. These are:
Synchronization is the process of allowing only one thread at a time to complete the particular task. It means when multiple threads executing simultaneously, and want to access the same resource at the same time, then the problem of inconsistency will occur. so synchronization is used to resolve inconsistency problem by allowing only one thread at a time.
Synchronization uses a synchronized keyword. Synchronized is the modifier that creates a block of code known as a critical section.
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
Using Volatile keyword
A volatile keyword is a field modifier that ensures that the object can be used by multiple threads at the same time without having any problem. volatile is one good way of ensuring that the Java program is thread-safe. a volatile keyword can be used as an alternative way of achieving Thread Safety in Java.
a=5 b=5 a=5 b=5 a=5 b=5 a=5 b=5 a=5 b=5
Using Atomic Variable
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.
Using Final keyword
Final Variables are also thread-safe in java because once assigned some reference of an object It cannot point to reference of another object.
Compilation Error in java code :- prog.java:14: error: cannot assign a value to final variable str str = "world"; ^ 1 error