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

Similar Messages

  • 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 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.

  • 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?

  • How can I transfer a variable to regexp_replace function

    Hi,
    In addition to my question from yesterday, I went up one (little) level for the next question.
    How can I transfer a variable to regexp_replace function?
    I am getting the value of the variables from from APEX Items.
    The value of item :P105_OLD_NAME should be replaced with the value from :P105_NAME APEX item.
    The projects in PROJECT_NAME field are separated by “:”
    select * from infoux_proj;
    HOSTNAME PROJECT_NAME
    host1 proj2:proj1
    host3 proj1
    host4 proj12:proj1
    host5 proj3
    host2 proj1:proj3:sunproj1
    this is my code:
    declare
    v_old_proj_list varchar(100);
    v_new_proj_list varchar(100);
    begin
    for host in (select a.hostname, project_name
    from infoux_proj a,
    (select hostname
    from PROJECT_NAMES_WITH_HOSTNAMES
    where name = :P105_OLD_NAME ) b
    where a.HOSTNAME=b.hostname)
    loop
    select project_name ,
    regexp_replace(project_name,'(^|:)(:P105_OLD_NAME)(:|$)','\1:P105_NAME \3') new_project
    into v_old_proj_list, v_new_proj_list
    from infoux_proj
    where hostname=host.hostname;
    update infoux_proj
    set project_name=v_new_proj_list
    where hostname=host.hostname;
    end loop;
    end;
    Thanks,
    Sheli

    Hi, Sheli
    Inside quotes, :p105_old_name will not be taken as a variable name. If you want to use the value of :p105_old_name in a string which its otherwise a literal, then you can concatenate the variable to the literal parts, using the || operator.
    You can do soemthing like this:
    REGEXP_REPLACE ( project_name
                , '(^|:)(' || :P105_OLD_NAME
                             || ')(:|$)'
                , '\1'       || :P105_NAME
                             || ' \3'
                )               AS new_projectI'll bet there's a much simpler way to do what you want. Instead of having two SELECTs, a cursor FOR loop and an UPDATE, you can probably do what you need to with just a single UPDATE or MERGE. It would be more efficient, too. If you'd like help, post CREATE TABLE and INSERT statements for all relevant tables and columns azs the exist before this code is run, a couple of sets of values for the bind variables, and the results you'd like to see (that is, the contents of the changed table) for each set, given the same sample data.
    Always say which version of Oracle you're using.

  • Can i Create Output Variable for DB Polling in BPEL 11g?

    Hi Team,
              I want to create the Output Variable for DB Polling,But when i double click on Reply Activity-->Create New Variable it is giving error message like "Can't Create output variable.The Selected operation doesn't have an Output Message".
    My Question is Can we create Output Variable for DB Polling, if Yes tell me the procedure to create the Output variable ?
    Regards,
    Kiran

    Hi Kiran,
    In these scenario generally runtime faults occurs so you can use the CatchAll activity and rethrow activity to complete the instance in error state. Also before the completion of the process if exception occurs you can rollback all the transaction.
    or
    you can use the Fault handling framework:
    Using Fault Handling in a BPEL Process - 11g Release 1 (11.1.1.7)
    Regards,
    Anshul

  • 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?

  • DSC alarm set and cleared without operator ack - the variable should be not alarmed and not acked

    We are deeply involved in porting our application from 7.1.1 to 8.6.1 under Windows XP.
    Our application  heavily depends on DSC and moving from 7.1.1 to 8.6.1 is actually much more than a simple porting....
    here is our last problem:
    it seems that there is no discrimination between 'active' alarms and 'acknowledged' alarms on a shared Variable  in case the 'ack Type' is set to 'USER'.
    Here is what happens:
    1) a Boolean shared variable is defined to be alarmed when 'high' (TRUE) and its ack type is set to 'USER' (the operator at our application must ack alarms).
    2) the Boolean var is set to TRUE -> it is declared alarmed (OK)  and not ack'ed (OK)
    3) the operator ack the variable -> it is declared alarmed (OK)  and ack'ed (OK)
    4) the Boolean var is set to FALSE -> it is declared not alarmed (OK)  and ack'ed (OK)
    5) the Boolean var is set to TRUE -> it is declared alarmed (OK)  and not ack'ed (OK)
    6) the Boolean var is set to FALSE -> it is declared alarmed (NOT OK!!!)  and not ack'ed (OK)
    7) the operator ack the variable -> it is declared not alarmed (OK)  and ack'ed (OK)
    This last case is the wrong situation: an alarm has been set and cleared without operator ack the variable should be not  alarmed  and not acked 
    Actually the variable returns OK only when ack'ed.
    see the attached project in which a small vi and a small shared variable lvlib allows to repeat the above steps.
    Note:
    A) same situation applies to 'double' shared variable
    B) under DSC version 7.1.1 everithing was OK 
    can anyone Help?
    Thank You Guglielmo Rozera
    Attachments:
    AlmAckTest.zip ‏18 KB

    Thank for your replay!
    I have tried to undeploy and deploy the library with ack type set to 'User' by default, and then run the vi but the behavior is always the same.
    The modification you suggest does not set 'User' ack type because data socket needs '2'  as 'User ' setting while property node needs '1' or (better) its own enumerated type.
    Anyway I've corrected the vi according to your suggestion and tried again but nothing changed...
    Here I attach the project modified with property node and an indicator to show what is the actual ack type
    I hope in your further investigations!
    Thank You
    Guglielmo 
    Attachments:
    AlmAckTest_2.zip ‏20 KB

  • Can we use Substitution variables in MAXL?

    Hi,
    Can we use substitution variables in MAXL script?
    I have to run this MAXL command for clearing a slice of ASO cube on V11.1.1.3.
    alter database Apname.DBname clear data in region 'CrossJoin({[2009]},{[Dec]})';
    I am planning to use Current_year & Current_month variables instead of hardcoding 2009 & Dec as I have to use this everymonth to clear the current months data.
    If it is allowed, what is the syntax?
    Is there any alternative apart from substitution variables?
    Appreciate your thoughts.
    Thanks,
    -Ethan.

    You would just use ampersand and the variable name instead of the hard coding e.g. &yearVar &periodVar.
    Not tried it on aso clears but in theory it should work as ...'CrossJoin({&yearVar},{&periodVar})';
    just change yearVar and periodVar for your substitution variable names.
    Cheers
    John
    http://john-goodwin.blogspot.com/

  • Can we use repository variables in bi publisher like in anwers

    can we use repository variables in bi publisher like in anwers
    if possible then how

    Yes,
    but you should be using Oracle BIEE as Datasource in order to use the variable of repository
    you 'll have to follow this syntax: valueof("variable")

  • How can I use environment variables in a controller?

    Hi all,
    How can I use environment variables in a controller?
    I want to pass a fully qualified directory and file name to FileInputStream and would like to do it by resolving an env variable, such as $APPLTMP.
    Is there a method somewhere that would resolve this??
    By the way,Did anyone used the class of "oracle.apps.fnd.cp.request.RemoteFile"?
    The following is the code.
    My EBS server is installed with 2 nodes(one for current,and other is for application and DB).I want to copy the current server's file to the application server's $APPLTMP directory. But the result of "mCtx.getEnvStore().getEnv("APPLTMP")" is current server's $APPLTMP directory.
    Can anyone help me on this?
    private String getURL()
    throws IOException
    File locC = null;
    File remC = new File(mPath);
    String lurl = null;
    CpUtil lUtil = new CpUtil();
    String exten;
    Connection lConn = mCtx.getJDBCConnection();
    ErrorStack lES = mCtx.getErrorStack();
    LogFile lLF = mCtx.getLogFile();
    String gwyuid = mCtx.getEnvStore().getEnv("GWYUID");
    String tmpDir = mCtx.getEnvStore().getEnv("APPLTMP");
    String twoTask = mCtx.getEnvStore().getEnv("TWO_TASK");
    // create temp file
    mLPath = lUtil.createTempFile("OF", exten, tmpDir);
    lUtil.logTempFile(mLPath, mLNode, mCtx);
    Thanks,
    binghao

    However within OAF on the application it doesn't.
    what doesnt work, do you get errors or nothing ?XX_TOP is defined in adovars.env only. Anywhere else this has to go?
    No, it is read from the adovars.env file only.Thanks
    Tapash

  • How can I set a variable number of values in a SQL IN clause?

    Hi,
    How can I set a variable number of values in a SQL IN clause without having to change the text of the SQL statement each time?
    I read the link http://radio.weblogs.com/0118231/2003/06/18.html. as steve wrote.
    SELECT *
    FROM EMP
    WHERE ENAME IN (?)
    But we need the steps not to create type in the system and would there be any other solution if we would like to use variable number of values in a SQL IN clause ?
    We are using JDeveloper 10.1.3.2 with Oracle Database 10.1.3.2
    Thanks
    Raj

    Hi,
    can you please explain why the solution from steve is not the right solution for you.
    regards
    Peter

  • How can I access global variables in a loaded Applescript?

    How can I access global variables in a loaded script, in Xcode, ApplescriptObjC? Basically, I have a global variable defined in my parent script using "property", and I need to modify objects connected to those variables inside of a loaded script.
    Example:
    Parent script:
    script AppDelegate
    property myTextField : missing value
    //linked to a text field object
    tell myScript to myAwesomeHandler_()
    end script
    Loaded script:
    on myAwesomeHandler_()
    myTextField's setStringValue_("The new Xcode is so glitchy ugh")
    //changes value of linked text field of parent script
    end myAwesomeHandler_
    The problem is, the variable is undefined in the Loaded script, and I need it to have the same value as the parent script, and I don't want to pass the variable through the Handler. Any ideas?

    I think want you are looking to do will need to be done in two steps. Because myTextField needs to be a property for the ObjectiveC part of the code you cannot turn it into a global.
    However if you make a temporary variable global assign the string to it in the handler then set myTextField off of it.
    global myTextFieldGlobal
    script AppDelegate 
    property myTextField : missing value 
    //linked to a text field object 
    tell myScript to myAwesomeHandler_() 
    myTextField's setStringValue_(myTextFieldGlobal)
    end script 
    on myAwesomeHandler_() 
    set myTextFieldGlobal to "The new Xcode is so glitchy ugh"
    //changes value of linked text field of parent script 
    end myAwesomeHandler_ 
    I know you stated you did not want the handler to return a value but I have to ask why? Global's, imo, are not a good idea and really should be used as a last resort.
    One other possibility is to pass a reference to the property to the handler. Not sure if that works in AS of if that would satisfy our requirement of not passing the variable through the handler
    <edit>
    Another though have you tried to define the property outside the script?  That is
    property myTextField : missing value
    script AppDelegate
    Not sure if that will work.
    You might also want to have a look at Scope of Properties and Variables Declared in a Script Object

  • Using action script 2 how can i send a variable value to a dynamic textbox on a different keyframe?

    using action script 2 how can i send a variable value to a dynamic textbox on a different keyframe?

    Thanks for your swift response.
    That sounds like a good solution, but the code I have on frame 2 is this
    timer = 0;
    countup = function(){
    timer++;
    countupInterval = setInterval(countup,100);
    If I added the same actionscript to frame 3 which has a dynamic textbox with a variable timer attached wouldn't it just put the timer back to 0? What I want is the last known value that was given when it was in frame 2.
    I am thinking of temple run here, I am trying to caculate the total distance(set in the timer variable) from the previous try.
    Hope this makes sense.
    Chazwick

  • What are Parameters? How are they differenet from Variables? Why can't we use variables for passing data from one sequnece to another? What is the advantage of using Parameters instead of Variables?

    Hi All,
    I am new to TestStand. Still in the process of learning it.
    What are Parameters? How are they differenet from Variables? Why can't we use variables for passing data from one sequnece to another? What is the advantage of using Parameters instead of Variables?
    Thanks in advance,
    LaVIEWan
    Solved!
    Go to Solution.

    Hi,
    Using the Parameters is the correct method to pass data into and out of a sub sequence. You assign your data to be passed into or out of a Sequence when you are in the Edit Sequence Call dialog and in the Sequence Parameter list.
    Regards
    Ray Farmer

Maybe you are looking for