Understanding of the Java volatile keyword

Source: Internet
Author: User

reprint: http://shmilyaw-hotmail-com.iteye.com/blog/1672779A multithreaded example raises the issue

Before discussing this keyword, look at a multithreaded sample code:

Java code
  1. Public class Racecondition {
  2. private static Boolean done;
  3. public static void Main (final string[] args) throws interruptedexception{
  4. New Thread (
  5. New Runnable () {
  6. public Void Run () {
  7. int i = 0;
  8. while (!done) {i++;}
  9. System.out.println ("done!");
  10. }
  11. }
  12. ). Start ();
  13. System.out.println ("OS:" + system.getproperty ("Os.name"));
  14. Thread.Sleep (2000);
  15. Done = true;
  16. SYSTEM.OUT.PRINTLN ("flag do set to true");
  17. }
  18. }

This part of the code is mostly set up with a static variable done. The primary thread of the main function will print some necessary information and then modify the value of the variable. Another derived thread is reading the done information and judging the next behavior based on the information. In general, one thread waits for another thread to modify a numeric result.

What is the result of running this piece of code?

Here's what happens in my specific execution environment:

Java code
    1. Os:linux
    2. Flag do set to true

The interesting thing is that the code executes here and does not completely exit, just keep stopping here.

From the literal meaning of the code, when the main function's main thread sets done to true, the derived thread should read this value and jump out of the loop, why didn't it jump out?

Don't worry, if we try to execute the above code in a different way, we'll find a different result:

If we enter the following command:

Java code
    1. JAVA-D32 racecondition

The results of this implementation will be:

Java code
    1. Os:linux
    2. Flag do set to true
    3. done!

So, it's really weird. What the hell is going on here?

First step analysis

In fact, the first problem is the way we execute the code when we execute it. The Java command execution pattern is related to the peace table. When we use Java racecondition on Linux platforms, Java defaults to server mode. And the back with Java-d32 racecondition, is manual instructions to use the client mode to execute. So the problem is the difference in the execution pattern.

Indeed, there are some differences between server mode and client mode for Java code execution. The server mode makes some optimizations to the code when it is JIT. Further, the problem ahead of us is the optimization of the server model. Why is the result wrong after such an optimization? We can look at the structure diagram of the JVM below to do the next analysis.

In the above illustration, each Java thread has its own separate stack, instruction register, cache, and other thread-local storage space. In this way, each time the thread executes, some local variables or incoming parameters can be processed within the thread's internal storage space. The key to this problem is the local storage space of the thread. After the previous code has been optimized, the thread reads to the done variable and reads a copy to the local storage space. This way, each time the thread accesses the variable, it does not run into the memory in which the variable was originally defined, but reads the copy of itself directly. That way, we'll see that the first way of execution doesn't end. The result we see in client mode is that without these optimizations, it is always read from the memory of the done variable.

So, what are the ways to solve the problem above?

One option, volatile

If there is a problem with the result, we can have several options, such as declaring done as an atomic data type, or using synchronized to access it. We can consider the volatile approach here.

Volatile means that it tells the JIT compiler not to optimize any of the modified variables. This way, each time a thread accesses a modified variable, each time it accesses the unique variable in memory, there is no other local copy.

Volatile provides a unique memory access address that can cause some misunderstanding. It seems that volatile variables appear to enable secure, multi-threaded access. Not really.

Volatile does not guarantee the atomicity of multiple thread accesses

For example, we have multiple threads to access a Web site's counter, assuming that the variable is count. Then each increment of the code for the variable is count++, and coarse and coarse seems to be satisfied with the volatile. There's actually going to be a problem.

Our actual execution details of the count increment operation are subdivided into three steps. 1. Read count,2. Increment count 3. Writes the modified value to memory. The problem is that when there are multiple threads accessing, there is a race condition that can lead to data errors.

Volatile also does not guarantee mutually exclusive access to threads

Unlike the Synchronized keyword, volatile has no strict restrictions on access variables. So you can have multiple threads at the same time read and write operations. This is not guaranteed to be thread-safe.

Performance aspects

Since volatile-modified variables are placed in memory, every time each thread accesses it, it accesses the memory. This is much slower than the direct access register or cache. If you have a large number of threads to access certain variables, you have to access the memory. Have a performance impact. In the actual computer architecture, the read performance of the volatile variable is very close to that of non-volatile variables and can almost be ignored. Only the write operation for volatile is relatively slow.

Volatile scenarios for some applications

Looking at the previous analysis, it makes people feel a little depressed. It seems that this thing doesn't work. From the previous analysis of performance, we can see an application. That is, volatile is a good option if only one thread is writing the data, and most of the threads are just data. Including the previous simple example, if it is only a common variable access, no special requirements, using volatile is a very simple solution.

and using thread synchronization mechanisms such as synchronized to restrict code, volatile can be used in a very simple way to meet some multithreaded access requirements.

For more detailed application of volatile, refer to this article.

Summarize

Volatile variables are a way to simplify multithreaded programming in some situations. It restricts the JIT optimization of multithreaded access and needs to be considered carefully in some cases where performance requirements are high.

Understanding of the Java volatile keyword

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.