Java multithreading guide for beginners (6): use volatile keywords with caution

Source: Internet
Author: User

The volatile keyword is believed to be clearly understood by readers who understand Java multithreading. The volatile keyword is used to declare simple type variables, such as int, float, and boolean data types. If these simple data types are declared as volatile, their operations will change to atomic level. But there are some restrictions. For example, n in the following example is not atomic:

Package mythread;

Public class JoinThread extends Thread
{
Public static volatile int n = 0;
Public void run ()
{
For (int I = 0; I <10; I ++)
Try
{
N = n + 1;
Sleep (3); // delay of 3 ms to make running results more random

}
Catch (Exception e)
{
}
}

Public static void main (String [] args) throws Exception
{

Thread threads [] = new Thread [100];
For (int I = 0; I <threads. length; I ++)
// Create 100 threads
Threads [I] = new JoinThread ();
For (int I = 0; I <threads. length; I ++)
// Run the 100 threads just created
Threads [I]. start ();
For (int I = 0; I <threads. length; I ++)
// Continue after all the 100 threads are executed
Threads [I]. join ();
System. out. println ("n =" + JoinThread. n );
}
}
If the operation on n is atomic, the final output result should be n = 1000. When the area code is executed, n is usually less than 1000, this indicates that n = n + 1 is not an atomic operation. The reason is that the simple variable declared as volatile does not work if the current value is related to the previous value of the variable, that is, the following expressions are not atomic operations:

N = n + 1;
N ++;
If you want to change this situation to an atomic operation, you need to use the synchronized keyword. The above code can be changed to the following form:
Package mythread;

Public class JoinThread extends Thread
{
Public static int n = 0;

Public static synchronized void inc ()
{
N ++;
}
Public void run ()
{
For (int I = 0; I <10; I ++)
Try
{
Inc (); // n = n + 1 is changed to inc ();
Sleep (3); // delay of 3 ms to make running results more random

}
Catch (Exception e)
{
}
}

Public static void main (String [] args) throws Exception
{

Thread threads [] = new Thread [100];
For (int I = 0; I <threads. length; I ++)
// Create 100 threads
Threads [I] = new JoinThread ();
For (int I = 0; I <threads. length; I ++)
// Run the 100 threads just created
Threads [I]. start ();
For (int I = 0; I <threads. length; I ++)
// Continue after all the 100 threads are executed
Threads [I]. join ();
System. out. println ("n =" + JoinThread. n );
}
}
The code above changes n = n + 1 to inc (), where the inc method uses the synchronized keyword for method synchronization. Therefore, exercise caution when using the volatile keyword. Instead of modifying a simple type variable with volatile, all operations on this variable are original operations, when the value of a variable is determined by the previous one, such as n = n + 1 and n + + +, the volatile keyword is invalid, the operation on the variable is atomic level only when the value of the variable is irrelevant to the previous value, for example, n = m + 1. This is the original level. Therefore, be cautious when using volatile. If you are not sure about it, you can use synchronized instead of volatile.

 

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.