Java Multithreading (i) Causes of thread safety problems

Source: Internet
Author: User

    • Java thread-to-memory mapping
      • The Java memory model specifies that all variables are stored in main memory, that each thread has its own working memory, that the thread's working memory holds the variables used by the thread to the master memory copy, and that all the operations of the thread on the variable (read, assign) must be in working memory, You cannot read and write directly to the variables in main memory. Variables in the other's working memory cannot be accessed directly between different threads, and the transfer of variable values between threads needs to be done in main memory.

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M00/87/42/wKiom1fY9G6SlMEaAADN4Ydb6jU757.png "title=" The thread and main memory mapping diagram. PNG "alt=" wkiom1fy9g6slmeaaadn4ydb6ju757.png "height=" 231 "width=" 672 "/>

    • Interaction between working memory and main memory

  • The Java memory model only guarantees that the operation must be executed sequentially, without the assurance that it must be executed consecutively.

  • The following eight actions to complete the

    • Lock (Lock): A variable that acts on the main memory and identifies a variable as a thread-exclusive state.

    • Unlock (Unlocked): Acts on the main memory variable, frees a variable that is locked, and the released variable can be locked by another thread.

    • Read (read): Acts on the main memory variable, transferring a variable value from main memory to the working memory of the thread for subsequent load actions to use.

    • Load: A variable acting on a working memory that places the value of a read operation from the main memory into a variable copy of the working memory.

    • Use: A variable that acts on the working memory, passing a variable value in the working memory to the execution engine, which is performed whenever the virtual opportunity is to a bytecode instruction that needs to use the value of the variable.

    • Assign (Assignment): A variable acting on a working memory that assigns to the working memory a value received from the execution engine and performs this operation whenever the virtual opportunity is assigned to a byte-code instruction that assigns a value to a variable.

    • Store: A variable acting on a working memory that transfers the value of a variable in the working memory to the main memory for subsequent write operations.

    • Write: A variable that acts on the main memory, which transfers the store operation from the value of a variable in the working memory to a variable in the main memory.

  • In performing the above eight basic operations, the following rules must be met

    • One of the read and load, store, and write operations is not allowed to appear separately.

    • A thread is not allowed to discard its most recent assign operation, that is, the variable must be synchronized to main memory after it has changed in working memory.

    • A thread is not allowed to synchronize data from the working memory back to main memory for no reason (no assign operation has occurred).

    • A new variable can only be born in main memory, and it is not allowed to use a variable that is not initialized (load or assign) directly in working memory. That is, the assign and load operations must be performed before a variable is implemented with the use and store operations.

    • A variable allows only one thread to lock it at the same time, and lock and unlock must appear in pairs.

    • If you perform a lock operation on a variable, the value of this variable in the working memory will be emptied, and the value of the variable initialized by the load or assign operation needs to be re-executed before the execution engine uses the variable.

    • If a variable is not locked by the lock operation beforehand, it is not allowed to perform a unlock operation on it, nor is it allowed to unlock a variable that is locked by another thread.

    • Before performing a unlock operation on a variable, you must first synchronize this variable into main memory (perform store and write operations).

    • Re-order

    • In order to improve performance when executing programs, the compiler and processor often reorder instructions.

    • The long sort has the following several

      • The re-ordering of compiler optimizations. The compiler can rearrange the execution order of the statements without changing the semantics of the single-threaded procedure.

      • Reordering of instruction-level parallelism. Modern processors use instruction-level parallelism to overlap multiple instructions. If there is no data dependency, the processor can change the order in which the statement corresponds to the machine instruction execution.

      • reordering of memory systems. Because the processor uses the cache and read-write buffers, this makes the load and storage operations appear to be executing in a disorderly order.

      • To ensure the visibility of the memory, the Java compiler inserts a memory barrier directive in place of the generated instruction sequence to suppress a particular type of handler reordering.

    • Memory barrier

    • Memory barrier (memory Barrier, or sometimes called Fence) is a CPU instruction that controls reordering and memory visibility issues under specific conditions. The Java compiler also prohibits reordering based on the rules of the memory barrier. The

    • Memory barrier has the following

      • Loadload Barrier: For such statements Load1; Loadload; Load2, the data to be read by the LOAD1 is guaranteed to be read before Load2 and subsequent read operations are accessed.

      • Storestore Barrier: For such a statement Store1; Storestore; Store2, the Store1 write operation is guaranteed to be visible to other processors before Store2 and subsequent write operations are performed.

      • Loadstore Barrier: For such a statement Load1; Loadstore; Store2, the data to be read is guaranteed to be read by the Load1 before Store2 and subsequent write operations are brushed out.

      • Storeload Barrier: For such a statement Store1; Storeload; Load2, ensure that Store1 writes are visible to all processors before Load2 and all subsequent read operations are performed. Its overhead is the largest of the four types of barriers. In most implementations of the processor, this barrier is a universal barrier that combines the functions of three other memory barriers.

      happens-before principle

      The
    • Java memory model has some "natural" happens-before relationships that exist without any Synchronizer assistance and can be used directly in the encoding. If the relationship between the two operations is not there and cannot be deduced from the following rules, they are not guaranteed to be sequential, and the virtual machine can reorder them arbitrarily.

    • Program sequence rules (pragram order rule): Within a thread, in the order of program code, the preceding operation precedes the operation.

    • Tube lock rule: A unlock operation first occurs after the lock operation facing the same lock.

    • Volatile variable rules (volatile Variable rule): A write operation to a volatile variable takes precedence over a read operation that faces this variable.

    • Thread Start rule: the Start () method of the thread object takes precedence over each action of this thread.

    • Thread finally rules (thread termination rule): All operations in the thread occur first in the termination detection of this thread, we can end with the Thread.Join () method, Thread.isalive () The return value of such a segment detects that the thread has terminated execution.

    • Thread interruption rule: the invocation of the thread interrupt () method first occurs when the code of the interrupted thread detects that the interrupt event occurred, and the thread.interrupted () method can be used to detect if there is an interrupt.

    • Object Finalization rule (Finalizer rule): An object initialization completes (the construction method execution completes) first occurs in its Finalize () method.

    • Transitivity (transitivity): If operation a precedes operation B, Operation B first occurs in Operation C, it can be concluded that operation a precedes operation C.

This article is from the Java Technology Stack notes blog, so be sure to keep this source http://stroll.blog.51cto.com/11038467/1852737

Java Multithreading (i) Causes of thread safety problems

Related Article

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.