"Go" JAVA Concurrency and multithreading--read sense (second-to-second process communication, shared memory mechanism)

Source: Internet
Author: User
Tags instance method volatile

Original address: https://www.cnblogs.com/edenpans/p/6020113.html

Reference article: http://ifeve.com/java-concurrency-thread-directory/

Among them, the race, thread safety, memory model, inter-thread communication, Java threadlocal class section content.

    • 1. Directory Overview
The basic concept of threading: Describes the advantages, costs, and concurrent programming models of threads.     How to create a running Java thread. Inter-thread communication, the mechanism of shared memory: Race conditions and critical regions, thread safety and shared resources and immutability. Java memory model, inter-thread communication, Java Threadlocal class, thread signal deadlock related, resource competition Related: Deadlock, how to avoid deadlock, hunger and fairness, insert casing lock dead, slipped conditions ( This condition has been changed by other threads during the check of a particular condition from a thread to the thread, causing the first thread to perform the wrong operation on the condition, lock, read lock and write lock, re-enter write dead, semaphore, block queue, thread pool, CAS (compare and swap theory), Synchronizer, non-blocking algorithm, Amdahl Law (ability to calculate efficiency gains after parallel operation of the processor).
    • 2. Race condition and critical area
It is not secure when multiple threads have access to the same resources and write to those resources.     Resources can represent: the same memory area (variable, array, or object), System (database, Web Services), or file. For a simple addition operation This.count = This.count + VALUE,JVM The order of execution of the instructions should be: From memory get This.count value to register to add value of register to register     Value write memory if two threads cross execution, one thread plus 21 threads plus 3, the final result may not be 5, but 2 or 3.     Race condition: Two threads when competing for the same resource, a race condition exists if the resource access order is sensitive.     Critical section: The code area that causes the race condition to occur becomes the critical section. A race condition can be avoided by proper synchronization in the critical section.
    • 3. Thread safety and shared resources
Code that allows simultaneous execution by multiple threads is called thread-safe code.     Thread-Safe code does not contain race conditions.     1. Local variable 1.1 The local basic type variable is stored in the thread's own stack, so local variables of the underlying type are threads-safe. 1.2. The object that the local object reference refers to is not stored in the thread's stack.     All objects are in the shared heap. Two pieces of code, whether they are the underlying type or the reference object, are local variables and are thread-safe because they are not being fetched by other threads.
public void SomeMethod () {    long threadsafeint = 0;    threadsafeint++;}
public void SomeMethod () {    Localobject localobject = new Localobject ();    Localobject.callmethod ();    METHOD2 (localobject);} public void Method2 (Localobject localobject) {    localobject.setvalue ("value");}
2. Object member object members are stored on the heap. If two threads update the same member of the same object at the same time, the code is thread insecure.
public class notthreadsage{    StringBuilder builder = New StringBuilder ();    Public Add (String text) {        this.builder.append (text);    }}

Thread Control escape judgment

The creation of a resource, using destruction is done within the same thread, and never out of control of that thread.

Even if the object itself is thread-safe, but the object contains other resources, perhaps the overall application is not thread-safe. 3. Thread safety and immutability immutable and read only differences: When a variable is read-only, the value of the variable cannot be changed, but it can change when other variables change. And the same will not change.
    • 4.java memory model
The Java memory model regulates how the Java Virtual Machine Works in conjunction with computer memory.

Each Java Virtual machine thread has its own line stacks, which includes information about the current execution point of the method called by this thread. A thread can only access its own line stacks. Local variables are visible only to the current thread.

The object is placed on the heap. Each thread has its own line stacks, if it is a basic type of variable, directly stored in the thread stack, if it is a reference to the object, then the reference address will be placed in the thread stack, and the object will be in the heap, it is possible that there are two threads referencing the same object at the same time.
public class Myrunnable implements Runnable () {public    void run () {        methodone ();    }    public void MethodOne () {        int localVariable1 =;        Mysharedobject localVariable2 =            mysharedobject.sharedinstance;        .... Do more with local variables.        Methodtwo ();    }    public void Methodtwo () {        Integer localVariable1 = new Integer;        .... do + with local variable.    }} public class Mysharedobject {    //static variable pointing to instance of Mysharedobject public    static final Mysha Redobject sharedinstance =        new Mysharedobject ();    Member variables pointing to both objects on the heap public    integer object2 = new integer;    Public integer object4 = new integer (n);    public long member1 = 12345;    public long member1 = 67890;}

After two threads are started, OBJECT3 is a MySharedObject,而Object2,Object4 是 MySharedObject中的 object2 和 Object4.Modern Hardware Memory Architecture

Bridging between the Java memory model and the hardware memory schema

The hardware memory schema does not differentiate between line stacks and heap. For hardware all lines stacks and heaps are distributed in main memory.          Partial-line stacks and heaps may appear in the CPU cache and registers inside the CPU. When objects and variables are stored in different memory areas of the computer, there are some problems: 1. The visibility of threads to shared variable modifications. -When two threads are distributed across different CPUs, part of the thread's variables are not flushed back to main memory, which may cause a different step.          You can use volatile to avoid. 2. Race conditions occurs when reading, writing, and checking shared variables. Multiple threads Modify the value of shared memory at the same time, such as:

Java synchronization blocks can be used so that only one thread can enter the critical section of the code at the same time.          The synchronization block also guarantees that all the accessed variables in the code block are read from main memory, and when the thread exits the synchronization block, all the updated variables are flushed back into main memory, regardless of whether the variable is declared volatile. The 5.java sync block Java synchronization block (synchronized block) is used to mark methods or blocks of code that are synchronized.          Used to avoid competition.               Java Sync Keyword: synchronized all other threads waiting to enter the synchronization block will be blocked until the thread that executes the synchronization block exits. Four different synchronization blocks: instance methods, static methods, synchronous blocks in instance methods, and synchronous blocks in static methods.               --are synchronous blocks on the method. Instance method synchronization:
  Public synchronized void Add (int value) {      This.count + = value;  }
Each instance of its method synchronization is synchronized on a different object. In this way, each instance method synchronization is synchronized on a different object, that is, the instance to which the method belongs, and only one thread can run in the instance method synchronization block.          One instance of a thread. static method synchronization:
public static synchronized void Add (int value) {    count + = value;}
Static method synchronization refers to synchronizing on the class object on which the method resides. A class in a Java virtual machine can only correspond to one class object, so only one thread is allowed to execute a static synchronization method in the same class.                    A class can be executed by only one thread at a time, regardless of which static synchronization method in the class is called. The synchronization block in the instance method:
  public void Add (int value) {    synchronized (this) {       This.count + = value;       }  }

The this that is used in the example is the instance itself that represents the call to the Add method. Objects enclosed in parentheses in the synchronization constructor are called Monitor objects.

Synchronous blocks in static methods:
public class MyClass {public    static synchronized void Log1 (string msg1, String msg2) {       Log.writeln (MSG1);       Log.writeln (MSG2);    }     public static void Log2 (String msg1, String msg2) {       synchronized (myclass.class) {          Log.writeln (MSG1);          Log.writeln (MSG2);}}}  
Two methods are not allowed to be accessed concurrently by a thread.           If the second synchronization block is not synchronized on the Myclass.class Synchronizer, both methods can be accessed concurrently by the thread. Java Synchronization Example:
public class counter{          Long Count = 0;        Public synchronized void Add (Long value) {       This.count + = value;     }  }    public class Counterthread extends thread{     protected Counter Counter = null;     Public Counterthread (Counter Counter) {        this.counter = Counter;     }     public void Run () {for        (int i=0; i<10; i++) {           counter.add (i);}}  }  public class Example {public    static void Main (string[] args) {      Counter Counter = new Counter ();      Thread  Threada = new Counterthread (counter);      Thread  threadb = new Counterthread (counter);      Threada.start ();      Threadb.start ();     }  }

Since two threads are all shared with one counter instance, add () is called synchronously, only one thread can be called, and the other needs to wait.
  public class Example {public    static void Main (string[] args) {      Counter Countera = new Counter ();      Counter Counterb = new Counter ();      Thread  Threada = new Counterthread (Countera);      Thread  threadb = new Counterthread (counterb);      Threada.start ();      Threadb.start ();     }  }
At this point, two threads can call the Add () method at the same time, because they are in separate instances.
    • 6. Thread Communication
The purpose of thread communication is to enable threads to send signals to each other. Way: 1. Communicating through shared objects
public class mysignal{  protected Boolean hasdatatoprocess = false;  Public synchronized Boolean hasdatatoprocess () {    return this.hasdatatoprocess;  }  Public synchronized void Sethasdatatoprocess (Boolean hasData) {    this.hasdatatoprocess = HasData;   }}
Two threads get a reference to a Mysingal shared instance for communication.   The method that gets the variable at the same time is set to the synchronous method, preventing thread inconsistency. 2. Busy Waiting (Busy wait)
protected Mysignal sharedsignal = ... while (!sharedsignal.hasdatatoprocess ()) {  //do nothing ... busy waiting}
Thread B has been waiting for the data.    But it feels like here and before getting a shared variable is a principle. 3.wait (), notify (), and Notifyall () wait () are left in a non-running state until another thread calls the Notify () method of the same object. At the same time, the thread must acquire a lock on the object to invoke.
public class Monitorobject{}public class mywaitnotify{  monitorobject mymonitorobject = new Monitorobject ();  public void dowait () {    synchronized (mymonitorobject) {      try{        mymonitorobject.wait ();      } catch ( Interruptedexception e) {...}  }} public void Donotify () {    synchronized (mymonitorobject) {      mymonitorobject.notify ();}}  }
When calling this object's notify (), there is a wait thread that is awakened randomly, and there is also a notifyall () method to wake all threads. Once the thread invokes the Wait () method, the lock on the held monitor object is freed, allowing other threads to call Wait () or notify (). At the same time, a thread is woken up not immediately to exit the wait () method until the call to notify ()     The thread exits its own synchronization block. 4. Loss of signal because notify () and Notifyall () do not save the method that calls them, the signals they send are likely to be lost before wait (), which must be kept in the signal class.
public class mywaitnotify2{  monitorobject mymonitorobject = new Monitorobject ();  Boolean wassignalled = false;  public void dowait () {    synchronized (mymonitorobject) {      if (!wassignalled) {        try{          Mymonitorobject.wait ();         } catch (Interruptedexception e) {...}      }      Clear signal and continue running.      wassignalled = false;    }  }  public void Donotify () {    synchronized (mymonitorobject) {      wassignalled = true;      Mymonitorobject.notify ();}}}  
It should be the use of a variable to record whether notify () has been called. 5. Fake wake-up sometimes for inexplicable reasons, threads may wake up without using Notify () and Notifyall (). To prevent false wakeup, the member variable that holds the signal checks whether it is its own signal, and if not, continues to wait ().
public class mywaitnotify3{  monitorobject mymonitorobject = new Monitorobject ();  Boolean wassignalled = false;  public void dowait () {    synchronized (mymonitorobject) {while      (!wassignalled) {        try{          Mymonitorobject.wait ();         } catch (Interruptedexception e) {...}      }      Clear signal and continue running.      wassignalled = false;    }  }  public void Donotify () {    synchronized (mymonitorobject) {      wassignalled = true;      Mymonitorobject.notify ();}}}  
6. Multiple threads waiting for the same signal while loop can also resolve when multithreading is waiting, only one thread needs to be awakened and is awakened using Nitifyall ().            7. Do not call wait () in a string constant or global object is one of the causes of false wakeup and may cause the signal not to be received. Enhancement (Monitor) is an object and module that implements mutually exclusive access to shared resources for multiple worker threads. The tube is implemented at a point in time, with a maximum of one thread executing one of his subroutines.
    • 6 Java ThreadLocal
Threadlocal in Java allows variables to be read and written only by the same thread. Created: private ThreadLocal mythreadlocal = new ThreadLocal () Access: Mythreadlocal.set ("Local Valu            E ");          String threadlocalvalue = (string) mythreadlocal.get ();          If you do not want to use coercion type conversions, you can create a generic threadlocal object. Private ThreadLocal MyThreadLocal1 = new threadlocal<string> ();

"Go" JAVA Concurrency and multithreading--read sense (second-to-second process communication, shared memory mechanism)

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.