Java Concurrency - Thread Safe

2024. 10. 27. 15:11JAVA & SPRING/자바

반응형

What is Thread Safe?


No matter how many threads access an object or a method in a business, when writing this business logic, there is no need to do any additional processing, and the program can also run normally, which can be called thread-safe.

 

 

What is Thread Unsafe?


When multiple threads access an object simultaneously, if one thread is updating the value of an object while another thread is reading the value of the object at the same time, it is possible to get an incorrect value. In this case, we need to take additional measures to ensure the correct result, such as using the Synchronized keyword to synchronize the execution of the code in this part.

 


Thread Safety Issues


public class ResultError {

    static int count;

    public static void main(String[] args) throws InterruptedException {
        Runnable r = ()->{
            for(int i = 0; i < 10000; i++){
                count++;
            }
        };

        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(count); // the result should be 20000
    }
}

The actual output result is far less than the theoretical result. This is because under multithreading, the scheduling of the CPU is allocated in units of time slices, and each thread can get a certain amount of time slices. However, if the time slice owned by the thread is exhausted, it will be suspended and give up the CPU resources to other threads, which may result in thread safety issues. 



Using a for loop with incrementing a value, execution steps are mainly divided into three steps, and it may be interrupted between each step of the operation.
1. Reading
2. Incrementing the value
3. Saving the updated value


When thread1 reads and increments the value, which is 0, the scheduling of the CPU switches to thread 2. Before saving the value, thread2 starts reading and incrementing the value, which is still 1. It causes a thread safety issue and leads to incorrect data results. this is the most typical thread safety issue, where the value is referred to as a shared variable or shared data.

 

 

Solve This Problem


To solve this problem, we may need such a solution: when there are multiple threads operating on shared variables, it is necessary to ensure that at the same time, only one thread is operating on this variable, and other threads must wait until the thread finishes processing the data. This method uses a tool called a mutex lock, which is a lock that can achieve the purpose of mutually exclusive access. That is, when shared data is locked by the thread that is currently accessing it, at the same time, other threads can only be in a waiting state until the current thread finishes processing and releases the lock.

In Java, a method or code block modified by the keyword synchronized can ensure that only one thread can execute at the same time. 

 

public class ResultErrorResoultion {

    static int count;

    public static void main(String[] args) throws InterruptedException {
        Runnable r = ()->{
            synchronized (ResultErrorResoultion.class) {
                for(int i = 0; i < 10000; i++){
                    count++;
                }
            }
        };

        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(count); // the result should be 20000
    }
}

 


In which scenarios do we need to pay extra attention to thread safety issues?


1. Accessing shared variables or resources.
Data will probably be accessed by several threads at once rather than just one. In this case, thread safety issues may arise.

2. There is a binding relationship between different data.
Sometimes, different data appears in groups, corresponding or bound to each other. For example, changing IP and port numbers. If these two operations are not bound together, it may happen that only the IP or port number is changed separately. At this time, if the information has been released, the information recipient may get a wrong binding result of IP and port number, thereby causing thread safety issues.

3. The class that is dependent on does not declare itself to be thread-safe.
When we use other classes, if the other party does not declare itself to be thread-safe, then in this case, performing concurrent multi-threaded operations on it may result in thread safety issues.

반응형