Can the operations on a volatile variable be interleaved?

volatile int a;
//thread A
int b = a;
b++;
a=b;
//thread B
int b = a;
b--;
a=b;
Does declaring 'a' as volatile permit interleaving of operations of threads A & B ?
int b = a;//thread A
int b = a;//thread B
b++; //thread A
b--; //thread B
a = b; //thread A
a = b; //thread B
I know that a synchronized block or a method does not allow this. I'm not sure of what volatile does... Please help!!!

Yes. The sequence you show absolutely can happen.
Volatile means exactly the following, nothing more, nothing less:
1. Every read and write of that variable will be against the master copy, no thread-local copies.
2. double and long will be read and written atomically. (All other types are always read and written atomically, regardless of whether they're volatile or not.)
In addition, note that plus-plus and minus-minus are not atomic, and declaring the variable volatile doesn't change that.
If thread T1 does b++; that consists of the following operations:
1. Read current value of b.
2. Add 1 to that value.
3. Store the new value back into b.
So even if b is volatile, if T2 is also executing b++; concurrently, you can have the following (say b starts at 1):
1. T1 read 1 from b.
2. T2 read 2 from b.
3. T1 add 1, result is 2.
4. T2 add 1, result is 2.
5. T1 store 2 in b.
6. T2 store 2 in b.
So even though we incremented twice, the value only increased by 1. This can happen whether b is volatile or not.

Similar Messages

  • My 15" MacBook Pro (early 2008) will not empty the trash can.The operation can't be completed because an unexpected error occurred (error code -8003).

    My 15" MacBook Pro (early 2008) will not empty the trash can.The operation can’t be completed because an unexpected error occurred (error code -8003).

    Just the Option key. Third from the left on the bottom row.
    If that does not work, try the more elaborate steps described here:
    http://reviews.cnet.com/8301-13727_7-20020873-263.html

  • Can operations on volatile variables be reordered

    Hi everybody,
    I am reading "Java Threads 3rd edition"(Oreilly). The book covers J2SE1.5 so it must also cover thread programming in the new JMM.
    In chapter5 at "The effect of reodering statements", there is an example code as shown below.
    public int currentScore, totalScore, finalScore;
    public void resetScore(boolean done){
      totalScore += currentScore;
      if(done){
         finalScore = totalScore;
         currentScore = 0;
    public int getFinalScore(){
      if(currentScore == 0)
         return finalScore;
      return -1;
    }Then the author explain that this can be a problem if JVM decide to do some reordering.
    Thread1: Update total score
    Thread1: Set currentScore == 0
    Thread2: See if currentScore == 0
    Thread2: Return finalScore
    Thread1: Update finalScore
    Then the author state that
    *"It doesn't make any different whether the variables are defined as volatile: statements that include volatile variables can be reordered just like any other statements"*
    As far as I know, if the currentScore is volatile then JMM must guarantee the happens-before relationship. If the second thread see the update of currentScore then the write to finalScore must happens before the write to currentScore and the second thread should return the correct value of finalScore.
    Do I misunderstand something?
    Regards,
    Chatchai Chailuecha
    www.devguli.com

    It used to be that volatile variable access only had a happens-before relationship with each other, but other non-volatile variable accesses could be re-ordered. Under the new JMM, volatile variable access is similar to synchronization, in that everything done before the write to a volatile variable is guaranteed to be visible to a thread that later does a read of that volatile variable. A volatile variable access can be thought of as a barrier across which instructions can not be reordered. So I think the author's statement is wrong under the new JMM.
    More here: http://www.ibm.com/developerworks/library/j-jtp03304/#2.0

  • Using volatile variables in j2me

    Hi
    I was wondering what are the consequences of using volatile variables in j2me application.
    Can someone elaborate on the issue?

    Not sure what you mean by consequances but I use them for basically communicating with Threads with good success.
    Do you have some specific concerns about them?

  • Can volatile variable be called as static variable for threads?

    I am trying to understand volatile variable, and it's uses. I was thinking of using it to make it shared variable between threads, but not between object instances.
    public class VolatileExample extends Thread {
      volatile int x = 1;
      public void f() {
           x++;
           System.out.println(Integer.toString(x));
        public void run() {
              for(int i = 0; i<20;i++){
                   f();
                   try { Thread.sleep(500); } catch(InterruptedException e) {}
        }now, if I create two threads in main method of the same VolatileExample class, say T1 and T2, how many times would volatile int x be instanciated? would there be just one copy of volatile int x created, no matter howmany threads I create?

    WHICH REMINDS ME: YOU DIDN'T ANSWER MY QUESTION AS TO
    WHETHER YOU UNDERSTAND THREADS' LOCAL COPIES OF
    VARIABLES VS. THE MAIN MEM COPYIn my understanding,
    local copies means each thread gets their own copy of a variable and they play with it separately. changing this variable in one thread does not chage value for another thread.
    main mem copy is the one accessed by all the threads. If one thread changes this value, it is reflected to all other threads using this variable.
    right?
    I tried using voaltile variable as shared variable like this:
    import java.io.*;
    public class VolatileIncrement {
      private int x = 1;
      public void f() {
           x++;
           System.out.println(Integer.toString(x));
      public String toString() { return Integer.toString(x); }
      class MakeThread extends Thread{
           public MakeThread(){
                System.out.println("starting MakeThread thread");
         public void run() {
              for(int i = 0; i<20;i++){
                   f();
                   try { Thread.sleep(500); } catch(InterruptedException e) {}
      public void createT() {
         Thread T2 = new MakeThread();
              T2.start();
         Thread T1 = new MakeThread();
              T1.start();
    }and created another class:
    import java.io.*;
    class TestVolatile
         public static void main(String[] args)
              VolatileIncrement vi = new VolatileIncrement();
              System.out.println("creating threads now...");
              vi.createT();
              System.out.println("Done Testing!!");
    }can this be called as correctly using non-static volatile variable as shared data?

  • Atomic operation and volatile variables

    Hi ,
    I have one volatile variable declared as
    private volatile long _volatileKey=0;
    This variable is being incremented(++_volatileKey)  by a method which is not synchronized. Could there be a problem if more than one thread tries to change the variable ?
    In short is ++ operation atomic in case of volatile variables ?
    Thanks
    Sumukh

    Google[ [url=http://www.google.co.uk/search?q=sun+java+volatile]sun java volatile ].
    http://www.javaperformancetuning.com/tips/volatile.shtml
    The volatile modifier requests the Java VM to always access the shared copy of the variable so the its most current value is always read. If two or more threads access a member variable, AND one or more threads might change that variable's value, AND ALL of the threads do not use synchronization (methods or blocks) to read and/or write the value, then that member variable must be declared volatile to ensure all threads see the changed value.
    Note however that volatile has been incompletely implemented in most JVMs. Using volatile may not help to achieve the results you desire (yes this is a JVM bug, but its been low priority until recently).
    http://cephas.net/blog/2003/02/17/using_the_volatile_keyword_in_java.html
    Careful, volatile is ignored or at least not implemented properly on many common JVM's, including (last time I checked) Sun's JVM 1.3.1 for Windows.

  • Can I create a VI to change the 'operator' name on the teststand report?

    I want the user to be able to type in a name, as well as other information, in a VI when a test begins. I do not want to create 'users' as I don't know who the testers will be.
    I want the user to log in as an administrator (or tester -- any generic login), then type in their name into a VI that pops up when the test is started. I would then like to take their name as a string variable and pass it through to teststand and have it appear in the 'operator' area on the report.
    How do i do this?
    Thanks in advance!
    Dave Neumann

    In your process model, you can modify the Locals.StationInfo.LoginName variable. The default process model does this in the "Get Station Info" subsequence with the expression "Parameters.StationInfo.LoginName = StationGlobals.TS.CurrentUser.LoginName". You could either replace that statement, or add another one after it.
    An easy way to create a prompt is with the Message Popup step type. To get input back from the user, edit the step properties and configure the message box. Under the Options tab you can select "Enable Response Text Box". Then you can enter a post-expression like "Parameters.StationInfo.LoginName = Step.Result.Response" to assign the name to the TestStand variable.

  • Trying to delete file from trash but get this: The operation can't be completed because the item "File name" is in use. All other files delete except this one. Please help

    Trying to delete file from trash but get this: The operation can’t be completed because the item “File name” is in use. All other files delete except this one. Please help

    Maybe some help here:
    http://osxdaily.com/2012/07/19/force-empty-trash-in-mac-os-x-when-file-is-locked -or-in-use//

  • I got a flashing folder with a question mark. I got a new hard drive and upgraded to 4 gigs and can't open anything or reload the operating system? Help?

    I got a flashing folder with a question mark. I got a new hard drive and upgraded to 4 gigs and can't open anything or reload the operating system? Help? FYI: I have been using boot camp with windows 7 and started getting a kernal_data_Page_error and it would reboot windows, i was trying to do a chkdsk on the next reboot, but thats when i started getting this issue. I have put in a new hard drive and went from 2 gigs to 4. I can not get the computer to do anything, even the monitor does not show anything now????

    Prep your new drive:
    Drive Preparation
    1. Boot from your OS X Installer Disc. After the installer loads select your language and click on the Continue button.  When the menu bar appears select Disk Utility from the Utilities menu.
    2. After DU loads select your hard drive (this is the entry with the mfgr.'s ID and size) from the left side list. Note the SMART status of the drive in DU's status area.  If it does not say "Verified" then the drive is failing or has failed and will need replacing.  SMART info will not be reported  on external drives. Otherwise, click on the Partition tab in the DU main window.
    3. Under the Volume Scheme heading set the number of partitions from the drop down menu to one. Click on the Options button, set the partition scheme to GUID (for Intel Macs) or APM (for PPC Macs,) then click on the OK button. Set the format type to Mac OS Extended (Journaled.) Click on the Partition button and wait until the process has completed.
    4. Select the volume you just created (this is the sub-entry under the drive entry) from the left side list. Click on the Erase tab in the DU main window.
    5. Set the format type to Mac OS Extended (Journaled.) Click on the Security button, check the button for Zero Data and click on OK to return to the Erase window.
    6. Click on the Erase button. The format process can take up to several hours depending upon the drive size.
    After formatting has completed quit DU and return to the installer. Install OS X.

  • Data folder can not be opened in finding " AirPort Time Capsule " The operation can not be completed because the original item for " data" does not exist .

    Hi
    I have a " AirPort Time Capsule " (firmware 7.7.3) When I try to open the data folder in "finder". Then I got the message  " The operation can not be completed because the original item for " data" does not exist". I have a lot of data and I can understand why I get this message?
    Anyone who can help? Thanks..
    Br. Bo

    Get a USB drive of 2TB or more.. assuming your TC is 2TB. Either preformatted Mac or plug into your Mac and format it standard Mac OS Extended Journaled in disk utility.
    Do a full archive of the TC. You do this using airport utility. Do not click the erase disk.. I marked in green.. just the archive.. that is to backup the internal disk to the USB disk. It is not fast.. take it that the process will go at around 40-50GB/hr.
    Once you complete the archive .. it is a direct image of the data on your TC.. you can then plug it into your computer directly.. and then try and open the files you lost.. if you cannot open them.. open disk utility and fix the permissions.
    http://osxdaily.com/2015/01/13/repair-disk-permissions-mac-os-x/
    Or try the methods apple recommends..
    OS X Yosemite: Set permissions for items on your Mac
    It is possible to fix things on the USB drive because it is locally mounted.. but you cannot fix it on TC which is network drive.

  • The operation can't be completed because one or more required items can't be found. (Error code -43)

    When I attempt to add files to...or copy to the desktop of my mac, my icloud (idisk ..the blue icon on my desktop) is giving this error:
    The operation can’t be completed because one or more required items can’t be found.
    (Error code -43)
    I've been searching for info on that error code, but I'm not find anything on (many different error codes, but not -43).

    I get an error -36.
    I did the dot_clean in the terminal.
    Did not fix it.

  • Trying to reload firefox and getting this message, when moving to the applications folder: "The operation can't be completed because you don't have permission to access some of the items."

    Been having problems with Firefox/internet for several days, and all my updates seemed current. I decided to try to reload and have removed the other icons/download attempts from the app file. When I try to drag the icon into apps, I now get this message:
    The operation can’t be completed because you don’t have permission to access some of the items.

    * Download a new copy of the Firefox program: http://www.mozilla.com/firefox/all.html
    * Trash the current Firefox application to do a clean (re)install.
    * Install the new version that you have downloaded.
    Your profile data is stored elsewhere in the [http://kb.mozillazine.org/Profile_folder_-_Firefox Firefox Profile Folder], so you won't lose your bookmarks and other personal data.

  • Cannot delete file: The operation can't be completed because the item "DataReferences" is in use.

    I have a My Book TB Drive where all of my Time Machine backups go to. I decided to delete some older version of backups. They ended up in my trash can. When I deleted the items in my trash can, all of them erased with the exception of one file. This file refuses to go! I have tried "Empty Trash", "Secure Empty Trash" and holding the Option Key + "Secure Empty Trash". Each time the I get the following error: The operation can’t be completed because the item “DataReferences” is in use.
    If I unplug the My Book TB Drvie, the file dissapears from the trash can. If I plug it back in, it reappears.
    I am not sure what to do anymore. Any suggestions?
    Thanks!
    MacMini
    Mountain Lion (Error originated in OS X)
    My Book TB (External Hard Drive)

    I found an article on how to allow third party apps. Posted it below just in case if anyone is interested.
    http://www.computeraudiophile.com/f11-software/your-security-preferences-allow-i nstallation-only-apps-mac-app-store-and-identified-developers-12789/
    Anyhow, I was able to do the double click on the trash it.I tried the "fast" version and the "really stuck" version and unfortunately, none of the options worked.
    Any other suggestions?

  • Iomega UltraMax 4Q PLUS the following message appears: The operation can not be completed because the item "FILE NAME" is in use. "

    Help, I need to solve. No speculation please bomas or attempts to restart, confirm that the HD is formatted for MAC and etc. .....
    Whenever I try to copy my files from my HDD Western Digital 2T for my new Iomega UltraMax 4Q PLUS the following message appears: The operation can not be completed because the item "FILE NAME" is in use. "
    I can not stand it anymore ...
    I need to work and not temnho more space on my machine.
    Scenario - iMac11, 10.6.8 + WD + 2 + 2T 4T Iomega UltraMax Plus, formatted for both Mac and connected via Firewire 800
    Trying to copy the message aborts the copy - "The operation can not be completed because the item" FILE NAME "is in use."

    Hello,
    As I said earlier, properly formatted for Mac.
    Mac OS Extended (Journaled)
    This HD is formatted for MAC factory, but I even did a few times in my attempts I can say that this is entirely correct formattingwith it - Mac OS Extended (Journaled)

  • Cannot empty trash: "The operation can't be completed because the item ...

    I've been having trouble emptying the trash. I get the following error, "The operation can’t be completed because the item "_file name_" is in use."
    I've tried unlocking the files, but the unlock doesn't seem to stick.
    I'm not sure if this is related, but a couple of months ago, I had a repair done and since then some of my software have required me to enter my license information again; apparently it looked as if I was running the programs on a different machine.
    Anyone have tips/solns?

    Thank you!
    I ended up sticking the startup disc in, restarting while holding down the "c" key, and "using the Reset Home Directory Permissions and ACLs function of the Reset Paswoord function of the Utilities menu."
    It worked perfectly; I now have an empty trash can.

Maybe you are looking for