Atomic solve the problem? The mind has this model on it

An article on the visibility of orderliness, Happens-before to get , to solve the problem in two concurrent three, today we talk about how to solve the problem of atomicity

The source of the problem is the atomic thread switch , but in the context of multi-core CPU, does not allow thread switching is not possible, the so-called "magic goes, Road ridge", the new rules come:

Mutually exclusive: that only one thread of execution

In fact, the above sentence means: modification of shared variables are mutually exclusive, that is to say when the thread A modification of shared variables can not be modified by other threads, this problem does not exist operation is interrupted, then how to achieve mutex it?

lock

Concurrent understanding partner can immediately think of a small lock this concept, and your first reaction is probably to use synchronized, here you listed three common synchronized usage:

public class ThreeSync {

    private static final Object object = new Object();

    public synchronized void normalSyncMethod(){
        //临界区
    }

    public static synchronized void staticSyncMethod(){
        //临界区
    }

    public void syncBlockMethod(){
        synchronized (object){
            //临界区
        }
    }
}

The contents of three kinds synchronized locks there are some differences:

  • For normal synchronization method, the lock is the current instance of the object, this usually refers to
  • For static synchronization method, the lock of the current class is Class object, such as ThreeSync.class
  • A method for synchronizing blocks, the object lock is synchronized in parentheses

I deliberately added the three synchronized code inside a comment "critical area" of the words, what is the critical region it?

The critical area: the code we need to be mutually exclusive execution of critical section to see

Here, the surface of cognitive and knowledge are all strings, how effective is the key to protecting critical section locks after, which is directly related to the bug if you will write concurrent, find out about this chapter, you will find that no matter implicit lock / built-in lock (synchronized) or display lock (lock) are looking to use this relationship, relationship, everything on the right, let me see

The above three methods can be used to lock the FIG expressed:

Before the thread enters the critical zone, try to lock lock (), the lock is successful, the critical section (for shared variables to be modified), thread holding the lock After you perform a critical section of code, execution unlock (), release the lock. For this model, we often use to describe the position to seize the toilet pit:

Java in early learning and understanding how I remember the lock, but the implementation of the code, we can easily ignore two things:

  1. What do we lock that?
  2. What is our protection?

The two words together is that you can play a role in protecting the lock of the critical areas of resource? So we want to further refine the top model

In reality, we are aware of their need to protect their own lock to lock something , after this sentence translated into the language of your actions you have clearly know:

  1. What is your locks
  2. What are you protected resources

CPU is not like our brains are so smart, we have to state clearly what our locks are and what we want to protect the resources, it will be protected by locks resources (shared variables) we want to protect

Take the figure, the resource R (shared variables) that we want to protect the resources, so we have to create lock resources to protect resources R R, attentive friends may find on the map a few questions:

There is a clear relationship between point R and LR
when we write programs, often in the mind of the model is right, but ignore this point relationship, leading to their lock can not play a role in protecting the resource R (with a lock of someone's home protection something to protect their homes or their own homes with lock something someone's home), and ultimately lead to concurrency bug, so when you're sketching, to find a clear relationship

LR dotted line pointing to the left unshared variable
protection with written procedures it is easy to do, which is to protect the resource uncertainty, direct hodgepodge, with LR resource to be protected and R is not necessary to protect the non-shared variables up , to cite two examples for you to understand the harm done

  1. When writing serial programs, is not recommended try ... catch the whole process, so ask if there are difficult to locate, the same reason, we use accurate lock to lock to protect our resources enough, no other meaning resources are not locked
  2. The more locks to protect things, the greater the critical section, a thread from the critical area to get out into the critical zone of the longer time, which allows other threads waiting time longer, so concurrent efficiency has declined, in fact, this problem is related to the size of the lock, will also do follow-up instructions

As the program ape or simply take the code explain more practical mind, let me see:

public class ValidLock {
    
    private static final Object object = new Object();
    
    private int count;
    
    public synchronized void badSync(){
        //其他与共享变量count无关的业务逻辑
        count++;
    }
    
    public void goodSync(){
        //其他与共享变量count无关的业务逻辑
        synchronized (object){
            count++;
        }
    }
}

This is not to say on the synchronized method is not good, just to remind you with a suitable lock granularity will be more efficient

In the program counter example, we will often write:

public class SafeCounter {

    private int count;

    public synchronized void counter(){
        count++;
    }

    public synchronized int getCount(){
        return count;
    }
}

The figure is above model shows the program:

Here we lock is this, to protect this.count. But some students think getCount method no need to add synchronized keyword, because it is a read operation, will not make changes to shared variables, if you do not add synchronized keyword, it is contrary to the article surveillance happens-before we rule on lock rule:

A lock for unlocking happens-before subsequent lock on the lock
that is written on the read count is likely to count is not visible, it leads to dirty read

Above we see this lock can protect multiple resources, the protection of that resource with a number of different locks can it? Look at a program:

public class UnsafeCounter {

    private static int count;

    public synchronized void counter(){
        count++;
    }

    public static synchronized int calc(){
        return count++;
    }
}

Look carefully eyes wide open, a lock is this, a lock is UnsafeCounter.class, they want to protect shared variable count, do you think? The following figure shows the line model is the face of the program:

Two critical section with two different locks to protect, there is no critical section mutually exclusive relationship, it can not protect the count, so this lock is meaningless

to sum up

  1. Atomic solve the problem is to mutually exclusive, it is to ensure that intermediate states are not visible outside
  2. Lock is the key to solving the atomic issues, we know exactly what the lock is, what resources are to be protected, the more important to know your locks can protect the protected resource (arrow pointing the figure)
  3. Effective critical region is an inlet and an outlet, more critical area to protect a resource, a resource that is there are multiple entry and exit multiple parallel, which did not play a mutex protection, critical area exists in name only
  4. Lock the door to protect their own resources is no need to lock the entire area, if the lock of the entire district, which seriously affected the activities of other owners (the problem of lock granularity)

In this paper, synchronized lock To illustrate how to solve the problem of atomicity, mainly to help people build a macro concept, used to solve atomic problems, so that subsequent lock no matter what you see, as long as the mind recall the model described in this section, you all will find a new name, the learning curve is very relaxed.

Here three concurrent problems orderly, visibility, atomicity have a solution, which is complicated by distance, so that we have a macro concept; but interviews and combat stress are the details, then we made far and near, and gradually see the details concurrent Incidentally interviewer who frequently asked questions

Soul questioning

  1. Multiple locks a resource there will be a problem?
  2. When required lock the cell, you can not lock a door?
  3. Bank transfer, system conversion and two others to turn themselves, what kind of lock granularity appropriate?

Improve productivity tools


Recommended Reading


Welcome to continued public concern number: "arch day a soldier."

  • Dry cutting-edge Java technology sharing
  • Productivity tools summary | Reply "Tools"
  • Analysis of interview questions and answers
  • Technical Data collection | Reply "Information"

Easy to read detective novels thinking fun learning Java technology stack-related knowledge, in line with the simplification of complex issues, problems specific abstract and graphical decomposition of the principle of progressive technical issues, technology continues to update, please stay tuned ......

Guess you like

Origin www.cnblogs.com/FraserYu/p/11570380.html