The Volitle keyword in Java

Source: Internet
Author: User

http://blog.csdn.net/liujinwei2005/article/details/6295666

Original posts: http://rwl6813021.javaeye.com/blog/349169

When studying Threadpoolexecutor, it was found that many of them usedVolatile variable. I do not know why, so did a search, research: which borrowed a lot of online information. In understandingBefore a volatile variable acts, you need to understand some concepts:

What is atomic manipulation?
The so-called atomic operation, which is "a non-interruptible or a series of operations," in the case of verifying that an operation is atomic, in a multithreaded environment, we can avoid just to protect the operation in the periphery with a high performance lock, and even with the aid of atomic operation, we can implement the mutex. Many operating systems provide an atomic operation version of-+-assignment for the int type, such as NT provides APIs such as InterlockedExchange, and Linux/unix also provides functions such as Atomic_set.

about atomicity in Java?
Atomicity can be applied to "simple operations" on top of all basic types except long and double. For operations such as reading and writing primitive type variables other than long double, you can guarantee that they will be manipulated as non-split (atomic) operations. Because of the JVM version and other problems, many other operations are not easy to say, for example, the + + operation in C + + is atomic operation, but in Java is not good to say. In addition, Java provides atomic classes such as Atomicinteger. And then use atomicity to control concurrency is troublesome, also prone to problems.

What is the volatile principle?
In JavaThe original meaning of the volatile keyword is "unstable, changing"
the difference between using volatile and not using volatile is that the JVM memory and the thread work memory are synchronized. the volatile guarantee variable is consistent between the thread working memory and main storage.
Actually is to tell the processor, do not put me into the working memory, please directly in main memory operation me.

Next is the test: (Better to find and analyze problems by testing)
This paper states that several kinds of shaping variables are opened and 100 threads are enabled to do the same + + operation, and the results are very different:
>>execute End:
>>atomic:100000
>>vinteger:38790
>>integer:68749
>>source i:99205
>>source vi:99286
That is to say, except Atomic, the others are wrong.

We have some questions to explain.

1: Why does it produce incorrect data?
Multithreading, because the simultaneous operation of an integer variable for multithreading in the case of large concurrent operations can not be synchronized, and Atom provides a lot of solutions for such thread security problems, so solve the problem of simultaneous read and write operations.


2: Why do synchronization problems occur?
Java multithreading in the operation of the variable, in fact, each line routines a separate copy for the I value (independent memory area), but the declared value of I is in the main memory area, when the value of I is modified, the thread will own memory area block I value copied into the main memory area, So it's possible that the I value that each thread gets is not the same, so there's a synchronization problem.


3: Why after using the volatile modifier integer variable, or not?
Because volatile only solves the problem of storage, that is, I value is just kept in a memory area, but i++ this operation involves acquiring I value, modifying I value, storing I value (i=i+1), here the volatile just solves the storage I worth the problem, As for the acquisition and modification of I values, there is no synchronization.


4: Since the synchronization cannot be done, why use the modifier of volatile?
One of the main reasons is convenience, because you can simply add a modifier, without having to do the object locking, unlocking the cumbersome operation. But I do not recommend this mechanism, because it is more prone to problems (dirty data), but also does not guarantee synchronization.


5: How does that solve the problem?
The first: Solve the problem with synchronous synchronized, but also reduce the performance of the system.
The second type: Using atomic data atomic variables, which is the atomic solution from the beginning of the JDK1.5, this is a better solution now.


6:atomic Basic principles of implementation?
First, the variables in the atomic are declared for volatile variables, so that the storage and reading of the guaranteed variables are consistent, all from the same memory block, and then atomic provides the Getandincrement method, which encapsulates the variable's + + operation, and provides the Compareandset method, to complete the lock and unlock operation of a single variable, the method used an unsafe object, and now do not know how this unsafe work (there seems to be no public source code). Atomic Although solve the problem of synchronization, but the performance will still have some loss, but the impact is not small, on-line testing for this aspect, about 50million of operation is 250ms:850ms, for most of the high-performance applications, should still be enough.

Package qflag.ucstar.test.thread;

Import Java.util.concurrent.atomic.AtomicInteger;

/**
* Test Atomic Synchronization
* @author Polarbear 2009-3-14
*
*/
public class Testatomic {

public static Atomicinteger astom_i = new Atomicinteger ();

public static volatile Integer V_integer_i = 0;

public static volatile int v_i = 0;

public static Integer Integer_i = 0;

public static int i = 0;

public static int endthread = 0;

public static void Main (string[] args) {
New Testatomic (). Testatomic ();
}

public void Testatomic () {

for (int i=0; i<100; i++) {
New Thread (New Integertestthread ()). Start ();
}

try {
for (;;) {
Thread.Sleep (500);
if (testatomic.endthread = = 100) {
System.out.println (">>execute End:");
System.out.println (">>atomic:/T" +testatomic.astom_i);
System.out.println (">>vinteger:/T" +testatomic.v_integer_i);
System.out.println (">>integer:/T" +testatomic.integer_i);
System.out.println (">>source I:/t" +TESTATOMIC.I);
System.out.println (">>source Vi:/T" +testatomic.v_i);
Break
}
}

} catch (Exception e) {
E.printstacktrace ();
}
}

}
Class Integertestthread implements Runnable {
public void Run () {
int x = 0;
while (x<1000) {
TestAtomic.astom_i.incrementAndGet ();
testatomic.v_integer_i++;
testatomic.integer_i++;
testatomic.i++;
testatomic.v_i++;
x + +;
}
++testatomic.endthread; It seems to be invincible! Is it atomic?
}
}

-----------------------------------------xx-----------------------------------xx----------------------------------------- ------

I continue to add:

In addition to Testatomic.endthread, the other variables are ignored. Specific explanations can be found in the notes.



Import Java.util.concurrent.atomic.AtomicInteger;
Import java.io.*;

/**
* Test Atomic Synchronization
* @author PYc 2009-3-29
*
*/
public class Testatomic {
public static final int n=10;
public static final int m=10000;
public static int perfect_result=m*n;
public static int endthread = 0;

Private PrintWriter out;//Enter the information into the text "OUT.txt" because the console buffer may not be sufficient.

Public testatomic () throws IOException
{
Out =new PrintWriter (
New BufferedWriter (
New FileWriter ("OUT.txt"));
}

public static void Main (string[] args) {
try{
New Testatomic (). Testatomic ();
}catch (Exception e) {
System.out.println (E.getmessage ());
}
System.out.println ("ok./nstatistical report:");
System.out.println ("Covered by" + (Perfect_result-endthread) + "times.");
}

public void Testatomic () {
Thread[] Td=new Thread[n];
for (int i=0; i<n; i++) {
Td[i]=new Thread (New Integertestthread (i+1));
}
for (int i=0; i<n; i++) {
Td[i].start ();
Out.println ((i+1) + "go.."); Here, if the run () method code is small, the complete completion information is immediately observable.
}
try {
Long temp=0; The last Endtread value is stored.
int count=1000; If the temp value exceeds 1000 repetitions, it can be considered as ending the program.
for (;;) {
Thread.Sleep (1); It is possible that the main thread is running too fast to adjust the sampling frequency.
if (Testatomic.endthread = = Perfect_result) {
Out.println ("==============/r/nperfect!/r/n=============="); Perfect Match!
Break
}
if (temp==testatomic.endthread) {
Out.println ("equal!!"); /There may be duplicates at the end of all threads running, or it may be that the main thread has sampled too quickly.
count--;//countdown ...
}
else {
temp=testatomic.endthread;//assigns a new value to temp.
count=1000;//Reset the countdown.
}
Out.println ("Endthread =" +testatomic.endthread);//There is a chance to observe that the current Endthread value is less than the last.
This is the key point!
if (count<=0)
{
Out.println ("/r/ni ' ll be crazy if I wait for that once again!/r/nfailed, omg! +_+");
Break
}
}
Out.close ();
}catch (Exception e) {
E.printstacktrace ();
}
}

Class Integertestthread implements Runnable {
private int id;
Public integertestthread (int i) {
This.id=i;
}
public void Run () {
int i=m;//fully guaranteed thread overlap run
while (i>0) {
try{
Thread.Sleep (int) (10*math.random ()));//Set the sleep time so that threads overlap as much as possible.
}catch (Exception e) {
++testatomic.endthread;//tests the "atomic" nature of the statement. Actually done the experiment, we know,
++i,i++, I=i+1 is no guarantee of atomicity.
We can learn from the final Endthread value is not equal to m*n.
i--;
}
Out.println ("************/r/n" +id+ "has completed!/r/n************/r/n");
}
}
}

The Volitle keyword in Java

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.