Java multi-thread programming trap Summary 1

Source: Internet
Author: User

Trap 1: Start the thread in the constructor

Start a thread in the constructor, like this:

Public Class
{
Public ()
{
This. x = 1;
This. Y = 2;
This. Thread = new mythread ();
This. thread. Start ();
}
}

What problems does this cause? If Class B inherits Class A, the constructor of Class A will be called before the constructor of Class B is called according to the Java class initialization sequence, the thread will also be started before B is fully initialized. When the thread runs with some variables in Class A, it may not be used as expected, because in the constructor B, you may assign new values to these variables. That is to say, two threads are using these variables, but these variables are not synchronized.

There are two ways to solve this problem: Set A to final and cannot inherit; or provide a separate start method to start the thread, rather than in the constructor.

Trap 2: incomplete Synchronization

The Effective Way to synchronize a variable is to use synchronized to protect it. Synchronized may be an object lock or a class lock, depending on whether you are a class method or an instance method. However, when you synchronize a variable in method A, you also need to synchronize the variable elsewhere, unless you allow weak visibility or even generate error values. Code similar to this:

Class
{
Int X;
Public int getx ()
{
Return X;
}
Public synchronized void setx (int x)
{
This. x = X;
}
}

The setter method of X is synchronized, but the getter method is not, so it cannot be ensured that the X obtained by other threads through getx is the latest value. In fact, the synchronization of setx is unnecessary here, because the write to int is atomic. This JVM specification has ensured that multiple syncs have no significance. Of course, if it is not int but double or long, both getx and setx need to be synchronized, because both double and long are 64-bit, both write and read operations are performed in two 32-Bit mode (depending on the JVM implementation. Some JVM implementations may guarantee that the read and write operations on long and double fields are atomic), without the guarantee of atomicity. Code similar to the above can be solved by declaring the variable volatile.

Trap 3: when an object is locked, the reference of the object is changed, resulting in synchronization failure.

Synchronized (array [0])
{
......
Array [0] = new ();
......
}

This is also a common error. Similar to the above Code, the synchronization block uses array [0] As the lock, but the reference pointing to array [0] is changed in the synchronization block. In this scenario, the first thread acquires the Lock of array [0], and the second thread waits because it cannot obtain array [0, after changing the reference of array [0], the third thread obtains the lock of the new array [0]. The Locks held by the first and third threads are different, the purpose of synchronization mutex is completely not achieved. In this way, the code is usually declared as a final variable or a lock object unrelated to the business is introduced to ensure that the synchronization block will not be modified or referenced.

Trap 4: Wait () is not called in a loop ().

Wait and policy are used to implement conditional variables. You may know that you need to call wait and Policy in the synchronization block to ensure atomicity and visibility of conditional changes. We often see that many codes have been synchronized, but do not call wait in a loop. Instead, we can use if or even have no conditions to judge:

Synchronized (LOCK)
{
If (isempty ()
Lock. Wait ();

}

If is used to determine the condition. What problems does this cause? You may call policy or policyall before determining the condition, so the condition has been met and will not wait. This is no problem. If the conditions are not met, the wait () method is called to release the lock and wait for sleep. If the thread is awakened under normal circumstances, that is, after the condition is changed, there is no problem. If the condition is met, continue to perform the following logical operation. The problem is that the thread may be accidentally or even maliciously awakened. Because the condition is not judged again, the thread executes subsequent operations when the condition is not met. Accidental wakeup may be caused by the call of policyall, which may be caused by malicious wakeup or automatic waking in rare cases (called "pseudo-Wakeup "). Therefore, to prevent the execution of subsequent operations if the conditions are not met, You must judge the conditions again after being awakened. If the conditions are not met, the system continues to wait and the conditions are met,.

Synchronized (LOCK)
{
While (isempty ()
Lock. Wait ();

}

It is even more serious to call wait without determining the conditions. Because notify may have been called before waiting, after wait is called, it cannot be guaranteed that the thread will wake up after waiting for sleep.

Trap 5: The synchronization range is too small or too large.

The synchronization range is too small, which may not achieve the goal of synchronization at all. A large synchronization range may affect performance. A common example of a small synchronization range is that two synchronous methods will also be called simultaneously. Remember that atomic + atomic! = Atomic.

Map map = collections. synchronizedmap (New hashmap ());
If (! Map. containskey (""))
{
Map. Put ("A", value );
}

This is a typical error. MAP is thread-safe, and containskey and put methods are also thread-safe. However, it is not necessarily thread-safe to call two thread-safe methods in combination. Because between containskey and put, other threads may put in a first, so it may overwrite the values set by other threads, resulting in loss of values. The method to solve this problem is to expand the synchronization scope, because the object lock can be reentrant, so there is no problem in synchronizing the same lock object on top of the thread security method.

Map map = collections. synchronizedmap (New hashmap ());
Synchronized (MAP)
{
If (! Map. containskey (""))
{
Map. Put ("A", value );
}
}

Note: To increase the lock range, make sure that the same lock is used. Otherwise, a deadlock may occur. Collections. synchronizedmap (New hashmap () uses the lock map itself, so there is no problem. Of course, we recommend using concurrenthashmap in the above situation. It has the putifabsent method to achieve the same purpose and ensure thread security.

There are also many examples of excessive synchronization scope, such as creating a new large object in the synchronization block or calling time-consuming Io operations (such as database operations and WebService operations ). You must specify the timeout time when you have to call time-consuming operations. For example, you must set connect timeout and read timeout when you use urlconnection to invoke a URL to prevent the lock from being exclusive and not released. When the synchronization range is too large, remove unnecessary synchronization operations from the synchronization block while ensuring thread security.

Trap 6: use volatile correctly

After jdk5 corrected the volatile semantics, volatile was widely used as a lightweight synchronization policy. For the strict definition of volatile, refer to JVM spec. Here we will only discuss what volatile can do and what it cannot do.
What can volatile do?
1) status flag, simulating the control mechanism. Common purposes such as whether the control thread is stopped:

Private volatile Boolean stopped;
Public void close ()
{
Stopped = true;
}

Public void run ()
{
While (! Stopped ){
// Do something
}
}

The premise is that do something does not contain blocking calls. Volatile ensures the visibility of the stopped variable. Reading the stopped variable in the run method is always the latest value in main memory.

2) security release, such as fixing the DLC problem. For details, refer to release


Private volatile iobufferallocator instance;
Public iobufferallocator getinsncmp ()
{
If (instance = NULL)
{
Synchronized (iobufferallocator. Class)
{
If (instance = NULL)
Instance = new iobufferallocator ();
}
}
Return instance;
}

3) read/write locks with low overhead

Public class cheesycounter
{
Private volatile int value;
Public int getvalue ()
{Return value ;}

Public synchronized int increment ()
{
Return Value ++;
}
}

Synchronized ensures update atomicity and volatile ensures inter-thread visibility.

What can't volatile be used?

1) it cannot be used as a counter.

Public class cheesycounter
{
Private volatile int value;
Public int getvalue ()
{Return value ;}

Public int increment ()
{
Return Value ++;
}
}

Because value ++ actually consists of three operations: Reading, modifying, and writing, volatile cannot guarantee that the sequence is atomic. The modification operation on value depends on the latest value of value. To solve this problem, you can synchronize the increment method or use the atomicinteger atomic class.
2) Non-variant with other variables
A typical example is to define a data range. The lower <upper.

Public class numberrange
{
Private volatile int lower, upper;

Public int getlower () {return lower ;}
Public int getupper () {return upper ;}

Public void setlower (INT value)
{
If (value> upper)
Throw new illegalargumentexception ();
Lower = value;
}

Public void setupper (INT value)
{
If (value <lower)
Throw new illegalargumentexception ();
Upper = value;
}
}

Although lower and upper are declared as volatile, setlower and setupper are not thread-safe methods. Assume that the initial state is () and both setlower (4) and setupper (3) are called at the same time. The final result may be (), which violates the constraints. To solve this problem, synchronize setlower and setupper:

Public class numberrange
{
Private volatile int lower, upper;
Public int getlower () {return lower ;}
Public int getupper () {return upper ;}

Public synchronized void setlower (INT value)
{
If (value> upper)
Throw new illegalargumentexception ();
Lower = value;
}

Public synchronized void setupper (INT value)
{
If (value <lower)
Throw new illegalargumentexception ();
Upper = value;
}
}


Cited by: http://java.chinaitlab.com/line/782806_3.html

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.