[Java concurrent programming practices]-thread security

Source: Internet
Author: User

Preface:

If there is no explicit synchronization to manage shared data, one thread may modify the data being used by other threads to generate unexpected results;

Writing thread-safe code is essentially managing access to States, which are usually shared and changeable.

State: in general, the state of an object is its data, which is stored in state variables, such as instance attributes or static attributes.

Sharing: a variable can be accessed by multiple threads;

Variable: The variable value can be changed within its lifecycle;

 

At any time, as long as more than one thread accesses a given state variable and a thread writes the variable, the synchronization mechanism must be used to coordinate the thread's access to the variable. Java provides the synchronized keyword, exclusive to a specific object to complete the so-called atomic operation.

 

I. Thread Security

When multiple threads access a class, if you do not need to consider the scheduling and alternate execution of these threads in the runtime environment, and there is no need for additional synchronization and other coordination between the caller's code. The behavior of this class is still correct, so this class is called "thread safe.

 

Ii. atomicity

1. What is Atomic?

The word Atomic has a relationship with atoms. It was once considered to be the smallest particle that cannot be further divided. Atomic in a computer means that it cannot be divided into several parts. If a piece of code is considered Atomic, it indicates that the Code cannot be interrupted during execution.

 

2. atomic operation:

Atomic operations are inseparable and will not be interrupted by any other tasks or events before execution;

An atomic operation is an operation that will not be interrupted by the thread scheduling mechanism. Once this operation starts, it will continue to run until the end, and there will be no context switch (switch to another thread) in the middle ).

 

3. classes that provide atomic operations:

The java. util. concurrent. atomic package provides many atomic operation classes.

Public class Test implements Runnable {// create AtomicIntegerprivate AtomicInteger atInteger = new AtomicInteger (); @ Overridepublic void run () {for (int I = 0; I <10; I ++) {/** Add the current value to 1 in atomic mode. That is to say, when a thread executes an atomic operation, it cannot be interrupted until the execution is completed. therefore, this method is thread-safe. */atInteger. getAndIncrement (); System. out. println (Thread. currentThread (). getName () + "... "+ atInteger. get (); try {Thread. sleep (1000L);} catch (InterruptedException e) {e. printStackTrace () ;}} System. out. println (Thread. currentThread (). getName () + ":" + atInteger. get ();} public static void main (String [] args) {Test test = new Test (); Thread th1 = new Thread (test ); thread Th1 = new Thread (test); th1.start (); th2.start ();}}

Iii. Lock

1. Internal lock

Java provides a built-in forced atomicity lock mechanism:

Synchronized block. A synchronized block has two parts: the reference of the lock object and the block protected by the lock;

The synchronized method is a brief description of the synchronized block that spans the entire method body. The lock of the synchronized method is the object of the method. (The static synchronized method obtains the lock from the Class object ).

Syntax:

Synchronized (lock ){

// Access or modify the shared status protected by the lock

}

 

The execution thread automatically acquires the lock before it enters the synchronized block. No matter whether it exits through the normal control path or throws an exception from the block, the thread Automatically releases the lock when giving up the control on the synchronized block. The only way to obtain the internal lock is to enter the synchronization block or method protected by the internal lock.

 

The internal lock plays the mutex lock role in Java, which means that only one thread can own the lock at most. When thread A tries to request A lock occupied by thread B, thread A must wait or block until thread B releases it. If B never releases the lock, A will wait forever.

 

At the same time, only one thread can run a code block protected by a specific lock. Therefore, synchronized blocks protected by the same lock are executed in an atomic manner without mutual interference.

 

Note: Atomicity is the same as it is used in transactional applications-a group of statements are run as separate and inseparable units.

 

2. reenter
When a thread requests a lock occupied by other threads, the request thread is blocked. However, internal locks are reentrant. Therefore, when a thread tries to obtain its own lock, the request succeeds. Re-entry means that all requests are based on "Every thread" instead of "every call.

 

Public class ReEntry implements Runnable {public synchronized void firstMth () {/** verify whether the internal lock can be reentrant: * both firstMth () and lastMth () are of the synchronized type, attempts to obtain the ReEntry lock before processing. * If the internal lock is not reentrant, the caller of lastMth () will never be able to obtain the ReEntry lock because the lock has been occupied, * This causes the thread to delay forever and waits for a lock that is never available. -- Re-access helps us avoid this deadlock */lastMth (); System. out. println ("enter firstMth... ");} public synchronized void lastMth () {System. out. println ("enter LastMth... ") ;}@ Override public void run () {firstMth ();} public static void main (String [] args) {Thread th = new Thread (new ReEntry ()); th. start ();}}

The re-entry implementation is to associate a request count and a thread that occupies each lock. When the count is 0, it is considered that the lock is not possessed. When a thread requests an unoccupied lock, the Count increases. Every time the occupied thread exits the synchronization block, the counter value decreases. When the counter reaches 0, the lock is released.

3. Lock protection status
A common lock rule is to encapsulate all the variable states in an object, and synchronize any code paths that access the variable state through the internal lock of the object to protect its security in concurrent access. This mode applies to many multithreading security classes.

For example, java. util. Vector class. In this case, all variables in the object state are protected by the internal lock of the object. If you forget to use the lock by adding a new code path method or code path, this lock protocol can also be easily destroyed.

Not all data requires lock protection-only variable data accessed by multiple threads.

4. Activity and Performance
Scenario:
Now let's assume that we declare the service () in the Servlet as synchronized, that is, the synchronization method. Therefore, only one thread can execute it at a time. This violates the original intention of the Servlet framework-Servlet can process multiple requests at the same time-and may cause customer dissatisfaction when the load is too high. If the Servlet is busy processing a complex operation, other users must wait until the current request is complete before it can process a new request. In a multi-CPU system, high real-time load still causes idle processors.

The running mode of the web application described above is a manifestation of "weak concurrency": the number of concurrent calls is limited, not the available processor resources, but the structure of the application itself.

By narrowing the scope of synchronized blocks to maintain thread security, the concurrency of Servlet can be easily improved.

Note: exercise caution when controlling synchronized blocks. You cannot break down an atomic operation into multiple synchronized blocks. However, you should try to separate time-consuming operations from synchronized blocks without affecting the sharing status. -- In this way, other threads are not blocked from accessing the shared state even during the execution of time-consuming operations.

 

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.