The Wayback Machine - https://web.archive.org/web/20241006004525/https://www.geeksforgeeks.org/thread-safety-and-how-to-achieve-it-in-java/
Open In App

Thread Safety and how to achieve it in Java

Last Updated : 24 Jun, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

  1. Using Synchronization.
  2. Using Volatile Keyword.
  3. Using Atomic Variable.
  4. Using Final Keyword.

Using Synchronization

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. 
 

Java




class A {
    synchronized void sum(int n)
    {
 
        // Creating a thread instance
        Thread t = Thread.currentThread();
        for (int i = 1; i <= 5; i++) {
            System.out.println(
                t.getName() + " : " + (n + i));
        }
    }
}
 
// Class B extending thread class
class B extends Thread {
 
    // Creating an object of class A
    A a = new A();
    public void run()
    {
 
        // Calling sum() method
        a.sum(10);
    }
}
class Test {
    public static void main(String[] args)
    {
 
        // Creating an object of class B
        B b = new B();
 
        // Initializing instance t1 of Thread
        // class with object of class B
        Thread t1 = new Thread(b);
 
        // Initializing instance t2 of Thread
        // class with object of class B
        Thread t2 = new Thread(b);
 
        // Initializing thread t1 with name
        //'Thread A'
        t1.setName("Thread A");
 
        // Initializing thread t2 with name
        //'Thread B'
        t2.setName("Thread B");
 
        // Starting thread instance t1 and t2
        t1.start();
        t2.start();
    }
}


 
 

Output: 

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.
 

 

Java




public class VolatileExample {
 
    // Initializing volatile variables
    // a, b
    static volatile int a = 0, b = 0;
 
    // Defining a static void method
    static void method_one()
    {
        a++;
        b++;
    }
 
    // Defining static void method
    static void method_two()
    {
        System.out.println(
            "a=" + a + " b=" + b);
    }
 
    public static void main(String[] args)
    {
 
        // Creating an instance t1 of
        // Thread class
        Thread t1 = new Thread() {
            public void run()
            {
                for (int i = 0; i < 5; i++)
                    method_one();
            }
        };
 
        // Creating an instance t2 of
        // Thread class
        Thread t2 = new Thread() {
            public void run()
            {
                for (int i = 0; i < 5; i++)
                    method_two();
            }
        };
 
        // Starting instance t1 and t2
        t1.start();
        t2.start();
    }
}


 
 

Output: 

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. 
 

 

Java




import java.util.concurrent.atomic.AtomicInteger;
 
class Counter {
 
    // Creating a variable of
    // class type AtomicInteger
    AtomicInteger count
        = new AtomicInteger();
 
    // Defining increment() method
    // to change value of
    // AtomicInteger variable
    public void increment()
    {
        count.incrementAndGet();
    }
}
 
public class TestCounter {
    public static void main(
        String[] args) throws Exception
    {
 
        // Creating an instance of
        // Counter class
        Counter c = new Counter();
 
        // Creating an instance t1 of
        // Thread class
        Thread t1 = new Thread(
            new Runnable() {
                public void run()
                {
                    for (int i = 1; i <= 2000; i++) {
                        c.increment();
                    }
                }
            });
 
        // Creating an instance t2
        // of Thread class
        Thread t2 = new Thread(
            new Runnable() {
                public void run()
                {
                    for (int i = 1; i <= 2000; i++) {
                        c.increment();
                    }
                }
            });
 
        // Calling start() method with t1 and t2
        t1.start();
        t2.start();
 
        // Calling join method with t1 and t2
        t1.join();
        t2.join();
 
        System.out.println(c.count);
    }
}


 
 

Output: 

4000

 

 

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. 
 

 

Java




public class FinalTest {
 
    // Initializing a string
    // variable of final type
    final String str
        = new String("hello");
 
    // Defining a method to
    // change the value of the final
    // variable which is not possible,
    // hence the error will be shown
    void method()
    {
        str = "world";
    }
}


Output:

Compilation Error in java code :- 
prog.java:14: error: cannot assign a value to final variable str
        str = "world";
        ^
1 error


Previous Article
Next Article

Similar Reads

How Does ConcurrentHashMap Achieve Thread-Safety in Java?
ConcurrentHashMap is a hash table supporting full concurrency of retrievals and high expected concurrency for updates. This class obeys the same functional specifications as Hashtable and includes all methods of Hashtable. ConcurrentHashMap is in java.util.Concurrent package. Syntax: public class ConcurrentHashMap<K,V> extends AbstractMap<
6 min read
Why Thread.stop(), Thread.suspend(), and Thread.resume() Methods are Deprecated After JDK 1.1 Version?
The Thread class contains constructors and methods for creating and operating on threads. Thread is a subclass of Object that implements the Runnable interface. There are many methods in Thread Class but some of them are deprecated as of JDK 1.1. In this article, we will understand the reason behind it. Deprecated methods are those that are no long
5 min read
Difference between Thread.start() and Thread.run() in Java
In Java's multi-threading concept, start() and run() are the two most important methods. Below are some of the differences between the Thread.start() and Thread.run() methods: New Thread creation: When a program calls the start() method, a new thread is created and then the run() method is executed. But if we directly call the run() method then no
3 min read
Naming a thread and fetching name of current thread in Java
Thread can be referred to as a lightweight process. Thread uses fewer resources to create and exist in the process; thread shares process resources. The main thread of Java is the thread that is started when the program starts. now let us discuss the eccentric concept of with what ways we can name a thread. Methods: There are two ways by which we c
5 min read
Type-Safety and Type-Casting in Java Generics
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. It is possible to create classes that work with different data types using Generics. An entity such as a class, interface, or method that operates on a parameterized type is a generic
4 min read
Different Ways to Achieve Pass By Reference in Java
There are two types of parameters one is Formal parameters and the second is Actual Parameters. Formal parameters are those parameters that are defined during function definition and Actual parameters are those which are passed during the function call in other Function. Showcasing the formal and actual parameters through code: Java Code // Java pr
5 min read
Java.lang.Thread Class in Java
Thread is a line of execution within a program. Each program can have multiple associated threads. Each thread has a priority which is used by the thread scheduler to determine which thread must run first. Java provides a thread class that has various method calls in order to manage the behavior of threads by providing constructors and methods to p
8 min read
Thread Interference and Memory Consistency Errors in Java
Java allows multithreading which involves concurrent execution of two or more parts of the program. It enhances CPU utilization by performing multiple tasks simultaneously. The threads communicate with each other by sharing object references and member variables. When Two threads access the same shared memory This communication in multithreading ca
5 min read
Lifecycle and States of a Thread in Java
A thread in Java at any point of time exists in any one of the following states. A thread lies only in one of the shown states at any instant: New StateRunnable StateBlocked StateWaiting StateTimed Waiting StateTerminated StateThe diagram shown below represents various states of a thread at any instant in time. Life Cycle of a Thread There are mult
6 min read
Daemon Thread in Java
In Java, daemon threads are low-priority threads that run in the background to perform tasks such as garbage collection or provide services to user threads. The life of a daemon thread depends on the mercy of user threads, meaning that when all user threads finish their execution, the Java Virtual Machine (JVM) automatically terminates the daemon t
4 min read
Lock framework vs Thread synchronization in Java
Thread synchronization mechanism can be achieved using Lock framework, which is present in java.util.concurrent package. Lock framework works like synchronized blocks except locks can be more sophisticated than Java’s synchronized blocks. Locks allow more flexible structuring of synchronized code. This new approach was introduced in Java 5 to tackl
5 min read
How to Create a Thread-Safe ConcurrentHashSet in Java?
Creating Thread Safe ConcurrentHashSet is not possible before JDK 8 because of the java.util.concurrent package does not have a class called ConcurrentHashSet, but starting with JDK 8, the newly added keySet (the default) and newKeySet() methods to create a ConcurrentHashSet in Java that is supported by ConcurrentHashMap. ConcurrentHashSet can be c
4 min read
Thread.sleep() Method in Java With Examples
Thread Class is a class that is basically a thread of execution of the programs. It is present in Java.lang package. Thread class contains the Sleep() method. There are two overloaded methods of Sleep() method present in Thread Class, one is with one argument and another one is with two arguments. The sleep() method is used to stop the execution of
4 min read
Importance of Thread Synchronization in Java
Our systems are working in a multithreading environment that becomes an important part for OS to provide better utilization of resources. The process of running two or more parts of the program simultaneously is known as Multithreading. A program is a set of instructions in which multiple processes are running and within a process, multiple threads
10 min read
run() Method in Java Thread
The run() method is available in the thread class constructed using a separate Runnable object. Otherwise, this method does nothing and returns. We can call the run() method multiple times. The run() method can be called in two ways which are as follows: Using the start() method.Using the run() method itself. Syntax: public void run() { //statement
3 min read
How to Create Thread using Lambda Expressions in Java?
Lambda Expressions are introduced in Java SE8. These expressions are developed for Functional Interfaces. A functional interface is an interface with only one abstract method. To know more about Lambda Expressions click here. Syntax: (argument1, argument2, .. argument n) -> { // statements }; Here we make use of the Runnable Interface. As it is
3 min read
Which Method Should We Use to Release a Lock from a Thread in Java?
In JVM we have the option of multithreading. It is an act of executing a complex process using virtual processing entities independent of each other. These entities are called threads. A thread gets blocked if it can't get access to the synchronized block. The Lock API provides the tryLock() method. The thread acquires a lock only if it's available
5 min read
Java Thread Priority in Multithreading
As we already know java being completely object-oriented works within a multithreading environment in which thread scheduler assigns the processor to a thread based on the priority of thread. Whenever we create a thread in Java, it always has some priority assigned to it. Priority can either be given by JVM while creating the thread or it can be gi
5 min read
Main thread in Java
Java provides built-in support for multithreaded programming. A multi-threaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.When a Java program starts up, one thread begins running immediately. This is usually called the main thread
4 min read
Thread Pools in Java
Background Server Programs such as database and web servers repeatedly execute requests from multiple clients and these are oriented around processing a large number of short tasks. An approach for building a server application would be to create a new thread each time a request arrives and service this new request in the newly created thread. Whil
9 min read
Implement Runnable vs Extend Thread in Java
As discussed in Java multi-threading article we can define a thread in the following two ways: By extending Thread class By implementing Runnable interface In the first approach, Our class always extends Thread class. There is no chance of extending any other class. Hence we are missing Inheritance benefits. In the second approach, while implementi
2 min read
Thread isAlive() Method in Java With Examples
Thread class in java provides numerous methods that are very essential in order to understand the working of threads as the thread stages are triggered by them. Java multi-threading provides two ways to find with the help of isAlive() and join() method.One thread gets to know when another thread has ended. Let us do depict stages of the lifecycle o
2 min read
Interrupting a Thread in Java
In Java Threads, if any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException. If the thread is not in the sleeping or waiting state, calling the interrupt() method performs normal behavior and doesn't interrupt
3 min read
Inter-thread Communication in Java
Prerequisite: Multithreading in Java, Synchronized in Java  Inter-thread communication in Java is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed. Note: Inter-thread communication is also known as Cooperation in Java. What is Polling
6 min read
Servlet - Single Thread Model Interface
Single Thread Model Interface was designed to guarantee that only one thread is executed at a time in a given servlet instance service method. It should be implemented to ensure that the servlet can handle only one request at a time. It is a marker interface and has no methods. Once the interface is implemented the system guarantees that there's ne
3 min read
Overriding of Thread class start() method
Whenever we override start() method then our start() method will be executed just like a normal method call and new thread wont be created. We can override start/run method of Thread class because it is not final. But it is not recommended to override start() method, otherwise it ruins multi-threading concept. // Java program illustrate the concept
2 min read
Overloading of Thread class run() method
Overloading of run() method is possible. But Thread class start() method can invoke no-argument method. The other overloaded method we have to call explicitly like a normal method call. // Java Program to illustrate the behavior of // run() method overloading class Geeks extends Thread { public void run() { System.out.println("GeeksforGeeks
2 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Article Tags :
Practice Tags :