"Java Concurrency Programming Practical" Reading Notes 2--object sharing, visibility, security release, thread closure, invariance

Source: Internet
Author: User
Tags closure volatile

The main content of this chapter is how to share and publish objects, so that they can be safely accessed by multiple threads simultaneously.

The visibility of memory

Make sure that when a thread modifies the state of an object, other threads can see the state change that occurred.

The novisibility in the above program may continue to loop because the read thread may never see the value of ready. A more bizarre phenomenon is that novisibility may output 0, because a read thread might see a value written to ready, but does not see a value written to number after that, which is called " reordering ." Multi-thread instruction reordering

Failure data

In short, it is possible to read outdated data in a program that lacks synchronization, that is, invalid data, as in the example above, when the thread is looking at the ready variable, it may get a stale value.

Non-atomic 64-bit operation

Although the resulting may be a failure value, at least this value is set by each thread before, not a random value. This security guarantee is also known as minimum security . The minimum security applies to most variables, but not for 64-bit numeric variables (double and long) of non-volatile types. Read and write operations for Java variables are atomic, but the JVM allows 64-bit read and write operations to be decomposed into 2 operations of 32. This way, when reading a non-volatile long variable, if the read and write operations on the variable are executed in a different thread, it is likely that a value of 32 is read to the lower 32 bits of the other value.

Locking and visibility

Volatile variable

Ensure that updates to variables are notified to other threads, and when the variable is declared as a volatile type, the compiler and the runtime will notice that the variable is shared, so the action on that variable is not reordered with other memory operations. The most recent write value is always returned when reading a variable of type volatile. The following procedure gives a typical use of volatile variables: check each status token to determine whether to exit the loop.

The semantics of volatile are not sufficient to ensure the atomicity of the increment operation (count++). The volatile variable should be used only if and only if all of the conditions are met:

1. Writing to a variable does not depend on the current value of the variable, or you can ensure that only a single thread updates the value of the variable

2. The variable is not included in the invariant condition with other state variables

3. No lock required when accessing variables

Description of volatile keywords in Java &&java concurrent programming: volatile keyword parsing

Release and Escape

A "publish" object means that the object can be used in code outside the current scope. This is known as escaping when an object that should not be published is published. The simplest way to publish an object is to save the object's reference to a public static variable;

Secure object Construction Process

Do not allow this reference to escape during the construction process. A common mistake in making this reference escape during the construction process is to start a thread in the constructor. When an object creates a thread in its constructor, whether it is a display creation or a hermit creation, the This reference is shared by the newly created thread. (In short, other objects in the object's constructor can get the current object's this reference and thus escape).

Thread closure

Do not share data, only the single-wire range access to data, avoid the use of synchronous way. This technique is heavily used to connection objects of swing and JDBC.

Ad-hoc Thread Closure

The responsibility of maintaining thread sealing is fully implemented by the program. Vulnerable, try to use stronger threading techniques (such as stack closures or threadlocal classes)

Stack closure

objects can only be accessed through local variables. One of the intrinsic properties of a local variable is that it is enclosed in the execution thread. They are in the execution thread's stack, and other threads cannot access the stack.

Threadlocal class

This class enables a value in a thread to be associated with the object that holds the value. Thislocal provides access interfaces or methods such as get and set, and when you use threadlocal to maintain variables, Threadlocal provides a separate copy of the variable for each thread that uses the variable, so each thread can independently change its own copy. Without affecting the replicas of other threads. Threadlocal objects are typically used to prevent the sharing of mutable single-instance or global variables. By saving the JDBC connection to the Threadlocal object (because the JDBC Connection object is not necessarily thread-safe), each thread will have its own connection.

This technique can be used when a frequently performed operation requires a temporary object, such as a buffer, and you want to avoid reassigning the temporary object each time it is executed. When a thread first calls the Threadlocal.get method, the rescue invokes InitialValue to get the initial value.

Non-denaturing

Another way to meet synchronization requirements is to use an immutable object, where the state cannot be modified after the object is created, all of its fields are final, and the object is created correctly (this reference does not escape). Mutable objects can still be used inside immutable objects to manage their state, such as

Final field

The final type of field cannot be modified, but if the object referenced by the final field is mutable (as in the previous example), then these referenced objects can be modified.

Example: using volatile types to publish immutable objects

Continue with the previous factorization example. The factorization Servlet performs two atomic operations: updates the results of the cache, and determines whether to directly read the factorization results in the cache by determining whether the values in the cache are equal to the requested values. Whenever you need to perform an operation atomically on a set of related data, you can create an immutable class to contain the data, such as:

Immutable container classes that cache values and their factorization results

@ImmutableclassOnevaluecache {Private FinalBigInteger Lastnumber; Private Finalbiginteger[] lastfactors; /*** If the arrays.copyof () method is not used in the constructor, the immutable object lastfactors in the domain can be changed by the extraterritorial code * then Onevaluecache is not immutable. */   PublicOnevaluecache (BigInteger i, biginteger[] factors) {Lastnumber=i; Lastfactors=arrays.copyof (factors, factors.length); }   Publicbiginteger[] Getfactors (BigInteger i) {if(Lastnumber = =NULL|| !lastnumber.equals (i))return NULL; Else      returnarrays.copyof (lastfactors, lastfactors.length); }}

Security release

Incorrect release, the correct object is destroyed

Immutable objects and initialization security

Any thread can safely access immutable objects without additional synchronization (state immutable, domain is final type, correct construction process)

Common patterns for Secure publishing

Mutable objects must be published in a secure manner.

Fact Non-mutable object

It is mutable, but the object will not be modified after it is published. In the absence of additional synchronization, any thread can safely use the fact immutable object that is released safely.

mutable objects

Requires not only secure publishing, but additional synchronization and thread safety to protect

Securely share objects

"Java Concurrency Programming Practical" Reading Notes 2--object sharing, visibility, security release, thread closure, invariance

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.