"Java concurrency Programming-read Notes" 02-sharing of objects

Source: Internet
Author: User

Writing the correct concurrency program requires proper management when accessing a mutable state.        It said earlier how to prevent multiple threads from accessing the same data at the same time by synchronizing, this chapter describes how to share and publish objects in order for objects to be securely accessed by multiple threads at the same time. The synchronized only implements atomic and critical areas. We also want a thread to modify the state of the object, and other threads can immediately see the state change. 3.1 Visibility In general, we cannot guarantee that threads that perform read operations can immediately see the values written by other threads, such as the following example:
 Public classnovisibility {Private Static BooleanReady ; Private Static intNumber ;  Public Static classReaderthreadextendsThread { Public voidrun () { while(!Ready )            {Thread.yield ();        } System.out.println (number); }    }     Public Static voidMain (string[] args)throwsException {NewReaderthread (). Start (); number= 42; Ready=true; System.out.println ("End of assignment"); }}
Although the above code seems to have no problem, it seems to work correctly. However, there are the following possibilities: 1, the thread outputs 0. (not tested) because the CPU will reorder the instruction encoding, causing "ready=true" to execute before "member=42". 2. Cycle of death. Although static variables are public, child threads may never see the modified value of the main thread. (because the child thread sees the value of the thread's own cache, if there is no appropriate triggering mechanism for the cache in the thread to re-trigger the update, then, even though the main thread modifies the static variable, the child thread still does not see the modified value) after the modified code, the case of a dead loop can occur:
 Public classnovisibility {Private Static BooleanReady ; Private Static intNumber ;  Public Static classReaderthreadextendsThread { Public voidrun () {inti = 0;  while(!Ready ) {i++; /*Releasing the print code below will trigger a memory update and the thread will be able to read the new ready value. *///System.out.println ("--into the loop body-");                /*notifies the system to discard execution of the thread, handing it over to other threads, which may be running from run state to*///Thread.yield ();} System.out.println ( number+ "," +i); }    }     Public Static voidMain (string[] args)throwsException {NewReaderthread (). Start (); Thread.Sleep (5);//TimeUnit.MILLISECONDS.sleep (ten);Number = 42; Ready=true; System.out.println ("End of assignment"); }}
First, the failure dataThe above because ready does not get the main thread to update the value of the static variable, or use the previous value to judge, called the failure data, this is a lack of synchronization performance. This failure data can lead to unexpected anomalies, corrupted data structures, imprecise computations, and infinite loops.
@NotThreadSafe  Public class Mutableinteger () {    privateint  value;      Public int get () {return  value;}      Public void Set (int value) {this. Value = value;}}
The above code looks fine, but is not thread safe.        If a thread calls set, another thread is just calling get, although set is a little earlier than get (even 1 nanoseconds), it does not guarantee that the value of the get is a new value or an old value. This is not a good place to synchronize only the set, but also to synchronize the get.
@ThreadSafe  Public class Mutableinteger () {    privateint  value;      Public synchronized int get () {return  value;}      Public synchronized void Set (int value) {this. Value = value;}}
Second, non-atomic 64-bit operationIn general, even the failure data, at least once valid, is not a random value. This security guarantee is called minimum security. There is a special situation that is not minimum security. Ordinary 64-bit numeric variables, such as double or long, in the Java memory model, both read and write are non-atomic operations. Because the JVM splits 64-bit read and write operations into two 32-bit operations. Therefore, at the time of concurrent read and write, it is possible to read a value of a high 32-bit value and another 32-bit low. This is a strange value. Third, locking and visibilitybuilt-in locks ensure that one thread can correctly view the execution results of another thread. In other words, for a lock m. All the operations of thread A before unlock m, when the B thread lock m, are able to see the result of the operation of the previous synchronization code block.locking is not just a mutex, but also includes memory visibility. Therefore, in order to ensure that all threads are able to see the latest paper for shared variables, all threads that perform read and write operations must synchronize on the same lock. Four, volatile variablesvolatile is a slightly weaker synchronization mechanism that resolves memory visibility. With this volatile, you can ensure that the update operation of the variable is notified to other threads.        After declaring a variable as a volatile type, the compiler and the runtime notice that the variable is shared: (1) The operation on the variable is not reordered with other memory operations, and (2) the volatile variable is not cached in the register or where the other processor is not visible. Therefore, the most recent value will always be returned when reading the volatile variable. In the above object definition, it can be changed to "private volatile int value;" In this way, the thread is not blocked and memory visibility is guaranteed. Therefore, volatile is a lightweight synchronization mechanism. (currently most processor architectures, the overhead of reading volatile variables is slightly higher than the cost of reading non-volatile variables) from memory visibility, write a volatile variable equivalent to unlock m, which reads volatile equivalent to lock M. However, excessive reliance on volatile is not recommended.volatile is generally recommended for status bit flags, and for composite operations, volatile does not satisfy atomicity. the locking mechanism can guarantee both atomicity and visibility. Volatile can only save visibility. 3.2 Release and overflowpublishing means that objects can be used in code outside the current scope. If an object that should not be published is published, an overflow occurs. (1) We often need to make sure that the object and the state within the object cannot be published. (2) If you need to publish an object, we want to ensure that the thread is secure at the time of publication, and that thread security cannot be compromised. Example 1: Publication of objects for public static variables. Look at the following example:
 Public Static Set<secret> knownsecrets;  Public void Initialize () {    new hashset<secret>();}
Here, if Knownsecrets's set is published, its internal secret object will be published indirectly. Example 2: A private variable is released, escaping its original scope. Look at the following example:
class unsafestates {    privatenew string[]{"AK", "AL"}    public string[] GetStates () {return  states;}}
If you publish states this way, the problem arises because any caller can modify the contents of the array, the original private variable, and the result is published.          When an object is published, all objects referenced in the object's non-private domain are published, including other objects that are reachable through non-private variables or methods. Example 3: An internal class instance is not sent. Look at the following example, the problem is even greater.
 public  class   Thisescape { public   Thisescape (EventSource source) {source.registerlistener{ ne W   EventListener () { public  void   OnEvent (Event e) {dosomething (); }}}}  public  void   dosomething () { //  ...  }}  
The above code is interpreted as follows: In the Thisescape constructor, an event listener is registered with EventSource. When the "Source.registerlistener" is executed, a thread is opened, and the DoSomething () method of the Thisescape object is executed when the event occurs. That is "this.dosomething ()". Both the main thread and thread B are visible to the "this". Thread B Essentially gets the "this" of the Thisescape object and then executes the dosomething () method. If the event occurs when the Thisescape constructor has not yet been initialized, then the "this.dosomething" method is called, but at this point, the Thisescape has not been initialized yet, and the other threads have already used the " This ", here, is this escape. This can lead to unexpected occurrences. When and only if the object's constructor returns, the object is in a consistent state that is predicted. do not let this reference escape in the constructor.
when the constructor starts a new thread, whether it is new threads () or through the Runnable interface, this is shared by the newly created thread.
Example 4: An enhanced version of the above example. As long as the thread is started, the thread can get to "this" and then use this when the problem occurs.
 Public classThisescape {PrivateString name;  PublicThisescape (String name) {NewThread (NewRunnable () {@Override Public voidrun () {System.out.println (thisescape. This. Name);        }}). Start (); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); }         This. Name =name; }     Public Static voidMain (string[] args) {NewThisescape ("Shenggang"); }}
Printing "ThisEscape.this.name" will appear null. Example 5: Using the Factory method, privatize the constructor to avoid this escaping.
 Public classSafelistener {Private FinalEventListener Listener; PrivateSafelistener () {Listener=NewEventListener () { Public voidonEvent (Event e) {dosomething (e);    }        }; }         Public StaticSafelistener newinstance (EventSource source) {Safelistener safe=NewSafelistener ();        Source.registerlistener (Safe.listener); returnsafe; }}
The above code, through the factory method, Newinstance, just creates a safe object. This time, and no threads are in use. When the safe is created, other threads can be used at will without any impact. 3.3 Thread-closed thread confinement means that data is not shared and data is accessed only within a single thread.        This is the simplest way to implement thread security. Typical use: Swing (the distribution thread that encloses the event). The JDBC Connection object (the connection object obtained from the connection pool is handled by a single thread in a synchronous manner). (1) The Ad-hoc thread is closed to complete the program to control the data can only be accessed in a thread. Very fragile, not recommended. (2) A special case where the stack closed thread is closed. objects can only be accessed through local variables. Because local variables are characterized by the fact that if they are in the stack of execution threads, other threads cannot access the stack. That is, the variables inside the method are not visible to other threads.
    Private intLoadtheark (collection<animal>candidates) {SortedSet<Animal>animals; intNumpairs = 0; Animal candidate=NULL; /*animals is enclosed in a method.*/Animals=NewTreeset<animal>();        Animals.addall (candidates);  for(Animal a:animals) {if(Candidate = =NULL|| !Candidate.isgood ()) {Candidate=A; } Else {                ++Numpairs; }        }        returnNumpairs; }
The above code, "animals" is closed in the method, that is, the local variable, then other threads are not visible. (3) The Threadlocal class maintains thread closure, and a better specification method is to use threadlocal. This class can be used to try to associate a value in a thread with an object that holds a value. Threadlocal provides methods such as get and set interface scenarios 1:threadlocal Most typical scenario: Connection database connection. In general, to avoid passing a connection variable each time the method is called, the general connection is created as a global database connection variable. If the multi-threaded case, everyone will take the use, and connection itself is not thread-safe.        Then, you can save the JDBC connection to the Threadlocal object, and each thread will have its own connection.        Essentially, threadlocal objects are used to place mutable singleton variables or global variables for sharing.        Scenario 2: A frequent operation requires a temporary object, which you do not want to reassign each time you execute, and you can use threadlocal. Scenario 3: A single-threaded program is ported to multiple threads, and you can move shared global variables into threadlocal to maintain thread security.about Threadlocal's understanding1. Instead of controlling concurrent access to the same object, Threadlocal assigns each thread a "thread-level local variable" that belongs only to that thread. 2, Threadlocal is essentially threadlocalmap, in connection, each time a new thread is created, a conn connection is taken out of the connection pool and placed in the threadlocal of the thread, which guarantees the unification of the thread's internal transactions. 3, threadlocal in the Threadlocalmap, use a weak reference (when there is no external strong reference, it will be GC off). After you run out of a threadlocal, if you do not remove it in time, it causes the key in the map to be null entry, and the corresponding value can never be reclaimed, causing a memory leak. 4, threadlocal use scene: Threadlocal is not to solve the problem of object sharing access, but a convenient way to avoid the frequent and complicated parameter passing. Most suitable for multi-threading, each thread requires an instance of object access, and this object is used frequently in that thread. (4) Invariant invariant objects can meet the requirement of synchronization. Immutable objects must be thread-safe.        The object can only be created from a constructor function. Note that although immutable objects can be declared with the final type, however, a reference to a Mutable object can be saved in the field of the final type of data.

"Java concurrency Programming-read Notes" 02-sharing of objects

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.