Java Concurrent Programming Practice Note (i)

Source: Internet
Author: User

Recently looking at "Java Concurrent programming Practical", I hope that I have the perseverance to read it.

The threads themselves have many advantages, such as the ability to take advantage of multiprocessor capabilities, simpler modeling, easier handling of asynchronous events, and more responsive user interfaces, but more need for program apes to face security issues. Look at the following example:

 Public class unsafesequence {    privateint  value;         /* returns a unique value */     Public int GetNext () {        return value++;    }}

The problem with unsafesequence is that if the timing is incorrect, then two threads will get the same value when calling GetNext, and Figure 1 shows this error condition. Although the increment operation value++ appears to be a single operation, it actually contains three separate operations: reading value, adding value to 1, and writing the result to value. Because the runtime may alternately execute operations between multiple threads, the two threads may perform read operations at the same time, so that they get the same value and add 1 to the value. The result is that the same values are returned in calls to different threads.

A common concurrency security problem, known as a race condition , is described in Unsafesequence. A race condition occurs when the correctness of a calculation depends on the alternating execution timing of multiple threads.

For example, a race condition in the deferred initialization:

 public  class   Lazyinitrace { private  hashmap<string,        string> instance = null  ;  public  hashmap<string, String> GetInstance () { if  (Instance = = null  ) {instance  = new  hashmap<string, S        Tring> ();     return   instance; }}

A race condition is included in the Lazyinitrace, which may break the correctness of this class. Assuming that thread A and thread B execute simultaneously getinstance,a see that instance is empty, and thus create a new HashMap entity, B also needs to determine whether instance is empty, and whether the instance is empty at this time, depending on the unpredictable timing. If instance is also empty when B is checked, then a different result may be obtained when you call getinstance two times, even if getinstance is usually considered to return the same instance.

Java provides a lock mechanism to solve this problem, but these are only a few mechanisms, to write thread-safe code, its core is to manage state access operations.

The state of an object refers to the data stored in a state variable, such as an instance or a static domain. If an object is stateless, it must be thread-safe.

  

 Public class Implements Servlet {    publicvoid  Service (ServletRequest request, servletresponse response)             throws servletexception, IOException {        int i = 1;        I+ +;        ...    }}

As with most servlets, Statelessservlet is stateless: it does not contain any fields, nor does it contain any references to the fields in other classes. The temporary state in the calculation is only available in local variables on the thread stack (this block requires a basic understanding of the JVM's memory allocation) and can only be accessed by the executing thread. There is no shared state between threads, and stateless objects are thread-safe because the behavior of threads accessing stateless objects does not affect the correctness of operations in other threads.

Second, use the lock to protect the state

  Built-in lock

  Java provides a built-in locking mechanism to support atomicity: synchronizing blocks of code. A synchronous code block consists of two parts: an object reference as a lock, and a block of code that is protected by this lock. A method that is modified by the keyword synchronized is a synchronous block of code that spans the entire method body, where the lock of the synchronization block is the object that the method call resides in, and generally does not do so, which affects efficiency.

Synchronized (lock) {

Access or modify shared status protected by a lock

}

Each Java object can be used as a lock that implements synchronization, which is called a built-in lock or a monitor lock. The thread automatically obtains the lock before it enters the synchronization code block and automatically releases the lock when it exits the synchronization code block.

There is no intrinsic association between an object's built-in lock and its state. Although most classes use built-in locks as an effective locking mechanism, the domain of an object is not necessarily protected by a built-in lock. When acquiring a lock associated with an object, it does not prevent other threads from accessing the object, and a thread can only block other threads from acquiring the same lock after acquiring the lock on the object. Each object has a built-in lock, just to eliminate the explicit creation of the lock object.

The use of built-in locks, which are common in development, is to encapsulate all mutable states inside the object and synchronize all access to the mutable state hungry code path through the object's built-in lock, so that no concurrent access occurs on the object, such as vectors and other synchronous collection classes.

  

In summary, it is the core meaning of this part to understand thread safety and why it is locked in the state of the object.

Java Concurrent Programming Practice Note (i)

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.