Java concurrent Programming Combat---Chapter III: Sharing of objects

Source: Internet
Author: User

In the absence of synchronization, the compiler, the processor, and the runtime can make some unexpected adjustments to the order in which the operations are executed. In a multithreaded program that lacks sufficient synchronization, the order in which memory operations are executed can be judged with little or no correct results.

Non-atomic 64-bit operation

When a thread reads a variable without synchronization, it may read an invalid value, but at least the value is set by a previous thread, not a random value. This security guarantee is also known as minimum security.

The Java memory model requires that both read and write operations for variables must be atomic, but for long and double variables of non-volatile types, the JVM allows 64 of read or write operations to be decomposed into two 32-bit operations. Therefore, it is not safe to use variables of a shared and variable type long or double in multi-threading, unless the volatile keyword or lock is used to protect against failure data issues.

The meaning of locking is not limited to mutex behavior, but also includes memory visibility. To ensure that all threads can see the latest values for shared variables, all threads that perform read or write operations must synchronize on the same lock.

Volatile

Volatile variables are used to ensure that update operations for variables are notified to other threads. When the variable is declared as a volatile type, the compiler and the runtime will notice that the variable is a shared variable, so the operation on that variable is not reordered with other memory operations. Volatile variables are not cached in registers or where other processors are not visible, and variables that read volatile types at a time always return the most recently written values.

The locking mechanism ensures both visibility and atomicity, while volatile variables only ensure visibility.

You should use a volatile variable only if all of the following conditions are true:

    • A write operation on a variable does not depend on the current value of the variable, or it ensures that only a single thread updates the value of the variable.
    • The variable is not included in the invariant condition along with other state variables.
    • There is no need to lock when accessing variables.

Release and escape of objects

Publish:"Publish" an object means that the object can be used in code outside the current scope.

For example, save a reference to the object to a place where other code can access it, or return a reference to the object in a non-private method, or pass the reference to a method in another class.

Code Demonstration: Save a reference to the object to a place where other code can access it.

save in a common static variable static set<secret> knowsecrets;  voidnew hashset<secret>();}     

escape:"escaping" means that an object that should not be published is published.

When you publish an object, other objects may be published indirectly. For example, if you add a Secret object to the Knownsecret, the Secret object will be published, because any code can traverse the collection and get a reference to the Secret object. Similarly, if a reference is returned from a non-private method, the returned object is published.

Code demonstration: A reference to a private object is returned in a non-private method.

Class unsafestates{    new string[]{"AK", "AL"};    Public return states;}}     

In the above code, the array states has escaped its scope because it was supposed to be a private variable that has been released.

Escape range: When an object A is published, all objects referenced in the non-private domain of A are also published. That is, an already published object A, able to reach other objects through non-private variable references and method calls, the objects that can be reached will be published along with a.

Here is a definition: "External method". If there is a Class C, for C, an "external method" refers to a method that is not fully defined by C, including methods that can be overridden in class C (neither the [private] method nor the [final] method).

When an object is passed to an external method, the object is at risk because you do not know what the external method will do to the object, so we need to use encapsulation. Encapsulation makes it possible to analyze the correctness of a program and makes it difficult to inadvertently break design constraints.

The factory method avoids escaping this reference in the construction method:

First understand how this reference escapes in the construction method. Let's look at a piece of code: Publish an instance of an inner class.

Class thisescape{public     thisescape (EventSource source) {        Source.registerlistener (            New void onEvent (Event e) {dosomething (e);}}); }}

In the preceding code, when Thisescape publishes EventListener, the Thisescape instance itself is also implicitly published because an instance of the inner class contains an implied reference to the Thisescapse instance. As long as other threads call this class before the Thisescape is constructed (the struct returns state), this is shared and recognized by the new thread (thread overflow).

The following code explains the above example:

Publicclass Thisescape {int I      = 100; public thisescape (int j) {new Thread (new Runnable () {@Override public void run () {System.out.println (i + j);}}). Start (); } public static void< Span style= "color: #000000;" > main (string[] args) {Thisescape ThisE = new Thisescape (100 ); }} 

The code above gives a special example of escaping, that is, this reference escapes in the construction method. When the internal new thread is released, the Thisescape instance in the outer package also escapes, so that I can be calculated with the I value and J. So when you publish an object from the constructor of an object, you simply publish an object that has not yet been constructed.

Common errors that use this reference to escape in a construction method: Start a thread in the constructor method, and invoke a rewritable instance method in the constructor method.

If you want to register an event listener or a startup thread in a construction method, you can use a private construction method and a common factory method to avoid unnecessary construction procedures. As shown in the following procedure:

PublicClass safelistener{private  Final EventListener listener; private Safelistener () {listener = new EventListener () {public void OnEvent (Event e) {dosomething (e);}}} public staticnew Safelistener (); Source.registerlistener (Safe.listener); return      

The code above is to register an event listener in the construction method, and the new thread cannot share and recognize safe before constructing the method.

Java concurrent Programming Combat---Chapter III: 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.