Several situations of Java thread safety (3) locks

1. Deadlock

Deadlock can only occur in the case of multiple locks, single lock will not cause deadlock, the above code:

public class Synchronized3Test {
    
    

    .....

    private void count(int newValue) {
    
    
        synchronized (monitor1) {
    
    
            x = newValue;
            y = newValue;
            synchronized (monitor2) {
    
    
                name = "aaa";
            }
        }
    }
    
	....

    private void setName(String newName) {
    
    
        synchronized (monitor2) {
    
    
            name = newName;
            synchronized (monitor1) {
    
    
                x = 0;
                y = 1;
            }
        }
    }
}

If the business needs to execute x , y , and then name when counting , when executing setName , execute name first , and then execute x, y . It happens that there are currently two threads that execute count and setName respectively , so that count executes After finishing monitor1 , execute monitor2 , and find that someone is executing monitor2 , and need to wait for him to be released; similarly, setName executes monitor2 , and when you need to execute monitor1 , you find that it is also occupied and needs to wait for release, so you wait for each other until the end of time,,, ,

Thus a deadlock occurs

2. Optimistic lock

It is a kind of optimistic concurrency control, and it is not locked. Some people call it optimistic locking

The scene that appears: in the database, read out a piece of data, perform operations on the data, and then write the data back to the database. Suppose someone modifies the piece of data during the read-out and write-back period. If we If the result is written back in time, then it must be inaccurate, and it can only be read out and then written back after calculation.

We judge that this situation will not happen often, and use the above optimistic method to deal with this problem and improve performance. We call this situation optimistic concurrency control

3. Pessimistic lock

Give up performance, lock before reading, then read, calculate, write back, and unlock


Optimistic locks and pessimistic locks are related to database design, not thread issues

Fourth, static synchronized use

see singleton pattern

Guess you like

Origin blog.csdn.net/qq_35178391/article/details/126052627