Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Java Concurrency -volatile keywords     - Getting the Linux shell expr use (Programming)

- Java implementation chain store binary tree (Programming)

- learning Linux ls command examples (Linux)

- CentOS yum install LNMP PHP5.4 version (Server)

- Verify the character set on MyCAT (Database)

- Hadoop 2.2.0 installation development environment (standalone pseudo-distributed mode) (Server)

- Docker Private Registry Installation Guide at CentOS6.X (Linux)

- RHEL6.5 install the latest version of Vim and increase support for the Python2.7.5 (Linux)

- awk variables (Linux)

- Ubuntu 14.04 to install file editor KKEdit 0.1.5 version (Linux)

- How to install Linux Kernel 4.0 On CentOS 7 system (Linux)

- DRBD rapid installation and deployment (Server)

- To install Ganglia configuration of experience under CentOS 5.5 (Linux)

- XP virtual machine under VirtualBox solve occupy 100% CPU problem (Linux)

- Linux server remote user to obtain root privileges prevention (Linux)

- Python Socket Network Programming (Programming)

- Java threads and thread pools (Programming)

- Linux environment to configure Apache + Django + wsgi (Server)

- Search Linux commands and files - which, whereis, locate, find (Linux)

- MySQL various log summary (Database)

 
         
  Java Concurrency -volatile keywords
     
  Add Date : 2018-11-21      
         
         
         
  Java language provides a weaker synchronization mechanism, namely volatile variable used to ensure that the notification of the update operation variables to other threads.

When the variable type is declared as volatile, the compiler and runtime will be noted that this variable is shared, and therefore the action is not on the variable memory operations together with other reordering, volatile variables are not cached in registers or on processor invisible place, so when reading the volatile variable always returns the latest value written. Access volatile variable does not perform locking operation and, therefore, does not make the execution thread is blocked, so volatile variable is a more lightweight synchronization mechanism than sychronized keywords.

One kind of volatile variables typical usage: checking a status flag to determine whether to exit loop

volatile boolean asleep;

while (! asleep)
      countSomeSheep ();

volatile variables are usually used with an operation is complete, interrupt, or state identification. Despite the volatile variables it can be used to represent other status information, but should be used with caution. For example, volatile enough to guarantee semantic increment operation (count ++) atomicity, unless you can ensure that only one thread of the variable write operation.

Locking mechanism to ensure both visibility and can guarantee atomicity, while volatile variable visibility only guarantee.

Use volatile should meet a number of conditions

First. Variable write operation does not depend on the current value of the variable, or you can ensure that only a single thread to update the values of variables

The variables are not included in the invariance conditions in conjunction with other state variables

Accessing locked variables are not required

Variable write operation does not depend on the current value of the variable, or you can ensure that only a single thread to update the values of variables

Common operations such as: i ++ operation, i write i need to rely on their own values, when there are multiple execution threads simultaneously i ++, A, B read the value of i, then ++ operator, the value may actually get ++ only once

The following code:

public class Volatiletest extends Thread {

        static volatile int a = 0;


      public void run ()
      {

        for (int i = 0; i < 10; i ++)
              try
        {
                a = a + 1;
                sleep (300);

            }
              catch (Exception e)
            {
            }
      }

      public static void main (String [] args) throws InterruptedException
      {
        Thread thread [] = new Thread [100];

        for (int i = 0; i < 100; i ++)
                thread [i] = new Volatiletest ();

        for (int i = 0; i < 100; i ++)
                thread [i] .start ();

        for (int i = 0; i < 100; i ++)
                thread [i] .join ();

        . System out.println ( "a:" + a);

      }
}

Run, you can learn a result is not necessarily equal to 1000, a lot of time to be less than 1000

Second. This variable is not included in the invariance conditions in conjunction with other state variables

Look at an example: There is a range of values is always less than or equal upper lower This is an invariant

  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;
          }
      }

In this way limit the scope of the state variables, the lower and upper fields are defined as volatile types can not be fully realized thread-safe class; thus still need to use synchronization. Otherwise, if you happen to execute two threads setLower and setUpper inconsistent values at the same time, then the range will be in an inconsistent state. For example, if the initial state is (0,5), the same time, the thread A calls setLower(4) Because using a volatile variable, the upper reading is 5, and the thread B calls setUpper(3) Similarly, since the variable is volatile, lower reading is 0, it is clear that the value of the cross into the two operations are not eligible, then by two threads are used to protect the invariant checks, making the final range value is (4,3) - - an invalid value. As for the other operations on the field, we need to make setLower () and setUpper () atomic operation - and the field is defined as a volatile type is impossible to achieve this purpose.

Third.from the previous know - locking mechanism to ensure both visibility and can guarantee atomicity, while volatile variable visibility only guarantee.

So volatile variable does not guarantee atomic lock operations.
     
         
         
         
  More:      
 
- Linux prohibit non-WHEEL user su command Detail (Linux)
- RHEL 7.1 compile and install Ganglia 3.7.1 (Server)
- Android official recommendation: DialogFragment create dialog (Programming)
- Linux6.1 / 6.5 dual-NIC Binding (Linux)
- Oracle bug Ora-04043 (Database)
- How to modify the Ubuntu terminal user name changed to red color (Linux)
- Dom4j change XML coding (Programming)
- Introduction and MongoDB CRUD (Database)
- Ubuntu install video playback software SMPlayer 14.9.0.7042 (Linux)
- How to modify the Emacs Major Mode Shortcuts (Linux)
- Process safety monitoring and protection under the Linux operating system (Linux)
- Use eCryptFS encrypt files and directories on Linux (Linux)
- Transplant spider to MySQL 5.6 (Database)
- How to install GIMP 2.8.16 in Ubuntu 16.04,15.10,14.04 (Linux)
- Getting Started with Linux system to learn: How to compress JPEG images on the command line (Linux)
- Linux environment variable configuration and save places (Linux)
- Git and GitHub use of Eclipse and Android Studio (Programming)
- Boot automatically remove Linux operating history records (Linux)
- printf PHP string operations () built-in function usage (Programming)
- Linux formatted partition error Could not stat / dev / sda No such file or directory Solution (Linux)
     
           
     
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.