Multi-thread programming learning 2 (concurrent access to objects and variables) and multi-thread programming Variables

Source: Internet
Author: User

Multi-thread programming learning 2 (concurrent access to objects and variables) and multi-thread programming Variables
I. ConceptsNon-thread security:When multiple threads concurrently access instance variables in the same object, the result is "Dirty read", that is, the obtained data is actually changed.Thread security:The value of the obtained instance variable is processed synchronously without dirty reading. Ii. synchronized Synchronization Method

1,Non-thread security problems exist in instance variables. If the variables are private variables in the method, there is no "non-thread security" problem, which is always thread security, this is because the variables in the method are private.

 

2,If the instance variable of the class is accessed and synchronized is not added to the method, multiple threads mistakenly modify the same variable value, leading to thread insecurity, this problem has been mentioned in the previous blog.

3,The method for calling the synchronized statement must be queued for running. In addition, you must keep the word "share" in mind. Only the read/write access to shared resources needs to be synchronized. If it is not shared resources, there is no need for synchronization at all. That is to say, if different threads do not access the same instance variable, the competition for resources by threads does not exist. Where is the thread security problem? So there is no need for synchronization.

4,The lock of the synchronized method is held by this class instance Object. That is to say, different synchronized methods in an Object actually hold the same lock, the same as the instance of the Object:

(1) thread A first holds the Lock of the object. Thread B can call non-synchronized methods in the object asynchronously. (2) thread A first holds the Lock of the object. If thread B calls the synchronized Method in the object, it needs to wait, that is, synchronize. 5,When dirty reading is bound to operate on instance variables, this is the result of "competing" instance variables in different threads. 6,"Reentrant lock": You can obtain your internal lock again, that is, when a thread gets an object lock in synchronized, when you request this object lock again, you can obtain the Lock of this object again. In addition, the reentrant lock also supports executing different synchronized methods of the same object lock in the Environment inherited by the parent and child classes in the order of calls.

 7,When the code executed by a thread encounters an exception, the lock held by the thread is automatically released.

 8,Synchronization does not have inheritance. That is to say, when the subclass inherits the synchronized Method of the parent class, the subclass method does not have synchronization or thread security. The synchronized keyword cannot be inherited, if the subclass method requires synchronization, manually add the synchronized keyword.

3. synchronized synchronous statement Block

1,The synchronized synchronization method has some drawbacks. In the synchronized synchronization method, the code that does not operate on instance variables also requires thread waiting and a lock mechanism. However, for the program, the code can be executed asynchronously to reduce the waiting time and improve the running efficiency. In this way, the synchronized synchronous statement block is available.

2,When two concurrent threads access the synchronized (this) Synchronous Code block in the same Object, only one thread can be executed for a period of time, the other thread must wait until the current thread executes the code block.

 

3,Like synchronized, the synchronized (this) code block also locks the current object. Of course, Java also supports the synchronization of "arbitrary objects" as lock objects. Most of the "arbitrary objects" are instance variables and method parameters in the format of synchronized (not this object ).

  • When the Lock Object of multiple threads is the same non-this object, only one thread can execute the code in the synchronized (non-this object) Synchronization block at the same time.
  • When the lock objects of multiple threads are not the same non-this object, the code in synchronized (non-this object) can be executed asynchronously.

Advantages of locking non-this object: if there are many synchronized methods in a class, synchronization can be implemented, but it will be blocked, thus affecting the running efficiency; however, if the synchronous code block lock is used to lock a non-this object, the program and synchronization method in the synchronized (non-this) code block are asynchronous and do not compete for this lock with other lock this object synchronization methods, this greatly improves the running efficiency.

4,The basis for determining whether multithreading is synchronous or asynchronous execution of synchronized is: (as long as the object is not changed, even if the object's attributes are changed, the running results are still synchronized .)

  • If multiple threads hold the same lock object, these threads are synchronized.
  • If multiple threads obtain lock objects separately, these threads are asynchronous.

5,The key word synchronized can also be applied to the static method. In this way, the Class corresponding to the current *. java file is locked. For more information, see my blog.

6,Pay special attention to the caching function of the String constant pool, because two String objects may reference the same memory space. Therefore, in most cases, synchronized does not use String as the Lock Object to synchronize synchronized code blocks, but uses other methods. For example, new Object () is used to instantiate an Object, but it is not stored in the cache.

7,The deadlock should be avoided in the program. The reason for the deadlock is that there is a cross reference between locks, and both threads are waiting for the other side to release the lock:

Iv. volatile keywords

1,In multithreading, values in private stacks and values in public stacks are not synchronized. What does it mean? The thread may modify the value of the variable in the memory in one place, while the thread reads the inconsistent variable value from the private stack in other places.

 

2,The key word volatile is used to make it visible on multiple threads. That is, force the value of the variable from the public stack, rather than the value of the variable from the private data stack of the thread.

Volatile private boolean running = false; // After defining a variable like this, it is emphasized that the multi-thread running reads data directly from the memory.

 

3,What is the difference between synchronized and volatile?

  • The keyword volatile is a lightweight Implementation of thread synchronization, so volatile has better performance than synchronized, and volatile can only be used to modify variables, while synchronized can be used to modify methods and code blocks.
  • Multi-threaded access to volatile will not be blocked, but synchronized will be blocked.
  • Volatile ensures data visibility, but does not guarantee atomicity. synchronized ensures atomicity, or indirectly, because it synchronizes data in private memory and public memory. (Atomicity: Atomic operations are an integral whole. No other thread can interrupt or check the variables in the atomic operation. It can ensure security without a lock)
  • In short, the keyword volatile solves the visibility of variables between multiple threads, while the synchronized keyword solves the synchronization of resource access between multiple threads.

4,The reason for the keyword volatile indicating non-thread security:

  • Read and load phases: copy the variable from the primary memory to the active memory of the current thread.
  • Use and assign phases: Execute Code to change the value of shared variables.
  • Store and write: Use the working memory data to refresh the value of the corresponding variable of the primary storage.

In a multi-threaded environment, use and assign appear multiple times, but this operation is not Atomic. That is to say, after read and load, if the count variable of the main memory is modified, the value in the thread working memory is not changed because it has been loaded, that is, the variables in the private memory and public memory are not synchronized, so the calculated results are different from expected, there is also a non-thread security problem.

For variables modified with volatile, the JVM Virtual Machine only ensures that the value loaded from the primary memory to the thread's working memory is up-to-date. For example, thread 1 and thread 2 are performing read and load operations, if the count value in the main memory is 5, the name will load the latest value. That is to say, the volatile keyword solves the visibility problem during variable reading, but cannot guarantee atomicity, lock synchronization is required for multiple threads to access the same instance variable.

5,In addition to the synchronized keyword, you can also use the AtomicInteget atomic class for synchronization. However, in a logical situation, atomic classes are not completely secure because although atomic methods are atomic, however, the call between methods is not atomic (synchronized is still required for synchronization ).

public class AddCountThread extends Thread {    private AtomicInteger count =new AtomicInteger(0);    @Override    public void run() {        super.run();        for (int i=0;i<10000;i++){            System.out.println(count.incrementAndGet());        }    }}

6,The keyword synchronized not only synchronizes multiple threads to access the same resource, but also synchronizes private variables in the thread working memory and public memory variables. It contains two features: mutual exclusion and visibility.

7,To learn multi-thread concurrency, we must focus on "external training is mutually exclusive and internal repair is visible ".

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.