A brief talk about Java Knowledge Point--multithreading

Source: Internet
Author: User
Tags volatile

  A) How multithreaded execution code is implemented

Suppose there are three threadsA,B,C,CPUby assigning a time slice to these three threads, the time slice is the execution time of each thread, and the time slice is CPU distributed through the algorithm loop. whenAafter executing a time slice, switch toCto execute,Calso executes a time slice before switching toBorAto execute, there is no guarantee that the thread will be switched to execute, but it will ensure that each thread that has been generated is executed, and that when the thread is switched, the state of the previous thread's execution is saved so that it can continue execution when it switches back.

II)   application of volatile

Volatile is a lightweight synchronizedthat makes shared variables "visible," and"visibility" means that when a thread modifies the value of a shared variable, another thread can read the modified value. using the appropriate volatile variable modifier has a lower execution cost than using synchronized because it does not cause context switching and scheduling of threads.

  What does the CPU do with modifying the volatile variable ?

To ensure processing speed, theCPU does not communicate directly with the memory, but instead reads the in-memory data into the internal cache, which is the CPU cache . When a thread modifies a volatile modified variable,theJVM sends an instruction to the CPU , sending the current the data in the CPU cache row (the smallest assignable unit in the CPU cache) is written back into memory (this operation is atomic and cannot be intervened by other threads while this operation is in progress).

And in manyCPUNext, otherCPUThe old value of the variable is also cached, so the old value of the continuation operation will still be problematic. So many CPU The Cache consistency protocol is implemented (and the protocol blocks two or moreCPUModification of memory area data), other CPU by sniffing the data that is propagated on the bus , the value of the variable in the cache row is checked for expiration (whether the data memory address in the cache row has been modified), and if it is found, the cached row of the cached variable is marked as invalid, and when the when the CPU goes back to manipulating this variable, it gets the latest value of the variable in memory and caches it.

   What is atomic operation?

Do not rely on other continuity to operate continuously.

such as the following pseudo-code:

  1  /**    * below is a pseudo-code   */  4   5  public  int   number;    7  System.out.println (number++) ;   9   volatile  int   number2;  10  

When a variable number that is not defined as volatile performs a self-increment operation, it goes through these three steps: Get the current value, add 1 to the current value, and then add 1 to the variable. Single-threaded mode is not a natural problem, but the problem of multi-threading is serious, it may be a thread to get the value of number after switching to thread two execution, and thread two after the completion of the self-increment step and then switch back to the thread one continues to execute, number initial value is 0, that experience after the scene value is how much? The answer is 1, I look at the use of multi-threaded number should be increased to 2, and in fact, when thread two executes after executing the thread, because the thread before the value of the number is 0, then the subsequent operation is performed on this 0.

However, after using the volatile keyword, it is not the same, and then switch back to the thread when it is executed, it will find that the variable value has expired need to obtain the most recent value, after the final execution, the result of number becomes 2.

three ) The realization principle and application of synchronized

Three forms of expression:

Normal synchronization method, the lock is the current instance object;

Static synchronization method, the lock is the class object of the current classes;

Synchronous code block, the lock is the object that is configured in parentheses;

  Synchronized implementations in the JVM :

Jvmis by entering and exitingMonitor (listener)object to implement a synchronous block of code, which relies on themonitorenter (enter listener)and theMonitorexit (Exit Listener)instructions. In theJavaafter the file is compiled,Monitorenterwill be inserted at the beginning of the synchronization code block,Monitorexitis inserted at the end of the method and at the exception, and any object has aMonitorassociated with it, when and aMonitoris held after it will be locked, that is, when a thread executes toMonitorentercommand, you try to get the object'sMonitorownership (attempting to hold it, i.e. acquiring an object lock) and waiting for it to be released if it is found to be unable to hold (locked).

IV)  common ways to avoid deadlocks

  ① prevents a thread from acquiring multiple locks at the same time, because attempting to acquire multiple locks may be associated with another thread trying to acquire a lock on the other, which leads to a deadlock.

② attempts to use a timed lock, using lock.trylock instead of an internal lock, because the lock has a timeout, which automatically releases the occupied lock when it reaches the specified time. Effectively avoids the occurrence of deadlocks.

A brief talk about Java Knowledge Point--multithreading

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.