Volatile vs synchronized

Does anyone have any opinions or references on the performance advantage (or disadvantage) of using a volatile variable as opposed to synchronizing on some object to reference it?

Here's a little code snippet I dreamed up and the results
public class Test {
     static volatile int thisInt = 0;
     static int thatInt = 0;
     static int theirInt = 0;
     public static void testVolatile() {
          long startTime = System.currentTimeMillis();
          for (int i = 0; i < 100000000; i++)
               thisInt = i;
          long stopTime = System.currentTimeMillis();
          System.out.println("Total time for volatile: " + (stopTime - startTime));
     public static synchronized void testSynchronized() {
          long startTime = System.currentTimeMillis();
          for (int i = 0; i < 100000000; i++)
               thatInt = i;
          long stopTime = System.currentTimeMillis();
          System.out.println("Total time for synchronized: " + (stopTime - startTime));
     public static void testFineSynchronized() {
          long startTime = System.currentTimeMillis();
          for (int i = 0; i < 100000000; i++) {
               synchronized (Test.class) {
                    theirInt = i;
          long stopTime = System.currentTimeMillis();
          System.out.println("Total time for fine synchronized: " + (stopTime - startTime));
     public static void main(String args[]) {
          Test.testVolatile();
          Test.testSynchronized();
          Test.testFineSynchronized();
}java version "1.3.1"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.1-b24)
Java HotSpot(TM) Client VM (build 1.3.1-b24, mixed mode)
The computer is a single processor PII 400Mhz
Total time for volatile: 1332
Total time for synchronized: 1572
Total time for fine synchronized: 95107

Similar Messages

  • Use of volatile modifier

    can any one explain me the use of volatile modifier

    What does volatile do?
    This is probably best explained by comparing the effects that volatile and synchronized have on a method. volatile is a field modifier, while synchronized modifies code blocks and methods. So we can specify three variations of a simple accessors using those two keywords:
    int i1; int geti1() {return i1;}
    volatile int i2; int geti2() {return i2;}
    int i3; synchronized int geti3() {return i3;}
    geti1() accesses the value currently stored in i1 in the current thread. Threads can have local copies of variables, and the data does not have to be the same as the data held in other threads. In particular, another thread may have updated i1 in it's thread, but the value in the current thread could be different from that updated value. In fact Java has the idea of a "main" memory, and this is the memory that holds the current "correct" value for variables. Threads can have their own copy of data for variables, and the thread copy can be different from the "main" memory. So in fact, it is possible for the "main" memory to have a value of 1 for i1, for thread1 to have a value of 2 for i1 and for thread2 to have a value of 3 for i1 if thread1 and thread2 have both updated i1 but those updated value has not yet been propagated to "main" memory or other threads.
    On the other hand, geti2() effectively accesses the value of i2 from "main" memory. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Of course, it is likely that volatile variables have a higher access and update overhead than "plain" variables, since the reason threads can have their own copy of data is for better efficiency.
    Well if volatile already synchronizes data across threads, what is synchronized for? Well there are two differences. Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block, if both threads use the same monitor (effectively the same object lock). That's the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with "main" memory. So executing geti3() does the following:
    1. The thread acquires the lock on the monitor for object this (assuming the monitor is unlocked, otherwise the thread waits until the monitor is unlocked).
    2. The thread memory flushes all its variables, i.e. it has all of its variables effectively read from "main" memory (JVMs can use dirty sets to optimize this so that only "dirty" variables are flushed, but conceptually this is the same. See section 17.9 of the Java language specification).
    3. The code block is executed (in this case setting the return value to the current value of i3, which may have just been reset from "main" memory).
    4. (Any changes to variables would normally now be written out to "main" memory, but for geti3() we have no changes.)
    5. The thread releases the lock on the monitor for object this.
    So where volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.
    I got the above information from the below link......
    http://www.javaperformancetuning.com/news/qotm030.shtml
    and also we can describe the volatile modifier as
    Volatile� A volatile modifier is mainly used in multiple threads. Java allows threads can keep private working copies of the shared variables(caches).These working copies need be updated with the master copies in the main memory.
    But possible of data get messed up. To avoid this data corruption use volatile modifier or synchronized .volatile means everything done in the main memory only not in the private working copies (caches).( Volatile primitives cannot be cached ).
    So volatile guarantees that any thread will read most recently written value.Because they all in the main memory not in the cache�Also volatile fields can be slower than non volatile.Because they are in main memory not in the cache.But volatile is useful to avoid concurrency problem.
    This above information i got from
    http://cephas.net/blog/2003/02/17/using-the-volatile-keyword-in-java/
    Thats all i think you understood what a volatile modifier is.And if you got any doubts still in Java you can reach me to [email protected]
    With Regards,
    M.Sudheer.

  • Synchronized {blocks} are not synchronized ?

    Hi
    I have a stored procedure containing a method with a synchronized block :
    public class MyClass {
    private static Connection conn;
    public static void insert(String stringData) {
    synchronized (conn) {
    //LOGGING
    Date startTime = new java.util.Date();
    ... some code ...
    //LOGGING
    Date stopTime = new java.util.Date();
    }I suppose that when a lot of concurrent users wil use the stored procedure, the synchronized block of code will not be executed at the same time. But when I do that my log dates are overcrossing, that means concurrent execution.
    How can I make this code really synchronized ??
    thanks,
    Xavier
    null

    radiatejava wrote:
    You mentioned there could be some thread caching - can you pls explain why/how ? Since the threads are not accessing the variable directly and instead they are querying the object using a method, why would the method return some old value ? I understand in case of direct access to the variable, a thread can cache the variable. Do you mean to say that threads will also cache the methods ? Otherwise, how is it possible to return the stale value. I am not expecting a blind answer like XClass is not thread safe (I too agree to this) but some explanation on how caching is being done with method calls too.You are thinking of it in a wrong way. It doesn't matter if methods are cached or not, methods are just static code blocks. The important thing to understand is that all data can be cached unless it is volatile or synchronized. The integer "inside" XClass is data, and that data might get cached, so e.g. getVar can return the cached value. It doesn't need to read the value from main memory. The same applies to setVar, it doesn't need to update the value in main memory.

  • Volatile is volatile or not ??

    Using "volatile" with two private variables accessed concurrently from two o more threads it seems don't work, at least for me.
    Using "synchronized' with the methods that access the variables, yes
    I.m using JDeveloper 3.2, with JDK 1.3 under WNT.4.0
    What's the problem ?
    Is "The Java Programming Language Spec" - 8.3.1.4 wrong ?

    Hi !
    Here follow two examples that probe, in my experience, that volatile is different form synchronize.
    My problems is that "The Java Lang. Spec. 8.3.1.4" say that they are equal. I don;t understand what it means.
    // ----------------------- Using_sync.java --------------------------------------------------
    // My examples Using_sync and Using_vol are variations of
    // the example [ sharing2.java ] of chapter 14
    // from "Thinking in Java, second edition" by Bruce Eckel : www.bruceEckel.com
    // To start, push the two buttons, in any order.
    // Problem :
    // The Java Language Specification, second edition, section "8.3.1.4 Volatile fields"
    // says that "synchronized" and "volatile" work in the same way
    // These examples probe that they work in different ways.
    // The Watcher threads watch the TwoCounter threads.
    // When count1 <> count2, the right label of the applet change
    // I use JDeveloper 3.2, with JDK 1.3, under WNT 4.0,
    // In "Using_sync", with "synchronized", the labels don't change, so, count1 == count2, for ever !
    // In "Using_vol", With "volatile", the labels, after a seconds, change all of them.
    // The Java Language Specification, second edition, section "8.3.1.4 Volatile fields"
    // says the "synchronized" and "volatile" work in the same way, and it give these
    // snippets of code :
    // <<<<<<<<<<<<<
    // class Test {
    //      static int i = 0, j = 0;
    // static synchronized void one() { i++; j++; }
    // static synchronized void two() {
    // System.out.println("i=" + i + " j=" + j);
    // This prevents method one and method two from being executed concurrently,
    // and furthermore guarantees that the shared values of i and j are both updated before
    // method one returns.
    // Therefore method two never observes a value for j greater than that for i; indeed,
    // it always observes the same value for i and j.
    // Another approach would be to declare i and j to be volatile : ( !!!??? )
    // class Test {
    //      static volatile int i = 0, j = 0;
    // static void one() { i++; j++; }
    // static void two() {
    // System.out.println("i=" + i + " j=" + j);
    // This allows method one and method two to be executed concurrently, . . . .
    // >>>>>>>>>>>
    // Note : the JTextFields may show different values even is the label say count1 == count2
    // It's just a problem of applet update.
    // The important thing is that if the synchTest() method detects any difference
    // the label change
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Using_sync extends JApplet {
    private static int accessCount = 0;
    private static JTextField aCount = new JTextField( "0", 14 );
    // to probe that the Watcher thread really runs.
    TwoCounter[] s;
    private JButton start = new JButton( "Start" );
    private JButton watcher = new JButton( "Watch" );
    private int numCounters = 12;
    private int numWatchers = 15;
    class TwoCounter extends Thread {
    public TwoCounter() {
    JPanel p = new JPanel();
    p.add( t1 );
    p.add( t2 );
    p.add( l );
    getContentPane().add( p );
    private boolean started = false;
    private JTextField t1 = new JTextField( 5 );
    private JTextField t2 = new JTextField( 5 );
    private JLabel l = new JLabel( "count1 == count2" );
    private int count1 = 0; // volatile vs synchronized ?
    private int count2 = 0; // volatile vs synchronized ?
    public void start() {
    if ( !started ) {
    started = true;
    super.start();
    public void run() {
    while ( true ) {
    synchronized( this ) {      // just synch this block so that synchTest() can execute
    t1.setText( Integer.toString( count1++ ) );
    t2.setText( Integer.toString( count2++ ) );
    try {
    sleep( 500 );
    } catch( InterruptedException e ) {
    System.err.println( "Interrupted" );
    public synchronized void synchTest() {
    if ( count1 != count2 )
    l.setText( "Unsynched" );
    accessCount++;
    aCount.setText( Integer.toString( accessCount ) );
    class Watcher extends Thread {
    public Watcher() {
    start();
    public void run() {
    while ( true ) {
    for ( int i = 0 ; i < s.length ; i++ )
    s[ i ].synchTest();
    public void init() {
    s = new TwoCounter[  numCounters  ];
    Container cp = getContentPane();
    cp.setLayout( new FlowLayout() );
    for ( int i = 0 ; i < s.length ; i++ )
    s[ i ] = new TwoCounter();
    JPanel p = new JPanel();
    // button start launch TwoCounter threads
    start.addActionListener( new ActionListener() {
    public void actionPerformed( ActionEvent e ) {
    for ( int i = 0 ; i < s.length ; i++ )
    s[ i ].start();
    p.add( start );
    // button watcher launch Watcher threads
    watcher.addActionListener( new ActionListener() {
    public void actionPerformed( ActionEvent e ) {
    for ( int i = 0 ; i < numWatchers ; i++ )
    new Watcher();
    p.add( watcher );
    p.add( new Label( "Access Count" ) );
    p.add( aCount );
    cp.add( p );
    public static void main( String[] args ) {
    Using_sync applet = new Using_sync();
    applet.numCounters = 2; // number of TwoCounter threads
    applet.numWatchers = 2; // number of Watcher threads : watch TwoCounter
    // bigger so that spy more
              JFrame frame = new JFrame( "synchronize Vs volatile" );
              frame.setDefaultCloseOperation( javax.swing.JFrame.EXIT_ON_CLOSE );
              frame.getContentPane().add( applet );
              frame.setSize( 450, applet.numCounters * 50 + 50 );
              applet.init();
              applet.start();
    frame.setVisible( true );
    // ----------------------- Using_vol.java --------------------------------------------------
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Using_vol extends JApplet {
    private static int accessCount = 0;
    private static JTextField aCount = new JTextField( "0", 14 );
    TwoCounter[] s;
    private JButton start = new JButton( "Start" );
    private JButton watcher = new JButton( "Watch" );
    private int numCounters = 12;
    private int numWatchers = 15;
    class TwoCounter extends Thread {
    public TwoCounter() {
    JPanel p = new JPanel();
    p.add( t1 );
    p.add( t2 );
    p.add( l );
    getContentPane().add( p );
    private boolean started = false;
    private JTextField t1 = new JTextField( 5 );
    private JTextField t2 = new JTextField( 5 );
    private JLabel l = new JLabel( "count1 == count2" );
    private volatile int count1 = 0; // volatile vs synchronized ?
    private volatile int count2 = 0; // volatile vs synchronized ?
    public void start() {
    if ( !started ) {
    started = true;
    super.start();
    public void run() {
    while ( true ) {
    t1.setText( Integer.toString( count1++ ) );
    t2.setText( Integer.toString( count2++ ) );
    try {
    sleep( 500 );
    } catch( InterruptedException e ) {
    System.err.println( "Interrupted" );
    public void synchTest() {
    if ( count1 != count2 )
    l.setText( "Unsynched" );
    accessCount++;
    aCount.setText( Integer.toString( accessCount ) );
    class Watcher extends Thread {
    public Watcher() {
    start();
    public void run() {
    while ( true ) {
    for ( int i = 0 ; i < s.length ; i++ )
    s[ i ].synchTest();
    public void init() {
    s = new TwoCounter[  numCounters  ];
    Container cp = getContentPane();
    cp.setLayout( new FlowLayout() );
    for ( int i = 0 ; i < s.length ; i++ )
    s[ i ] = new TwoCounter();
    JPanel p = new JPanel();
    // button start launch TwoCounter threads
    start.addActionListener( new ActionListener() {
    public void actionPerformed( ActionEvent e ) {
    for ( int i = 0 ; i < s.length ; i++ )
    s[ i ].start();
    p.add( start );
    // button watcher launch Watcher threads
    watcher.addActionListener( new ActionListener() {
    public void actionPerformed( ActionEvent e ) {
    for ( int i = 0 ; i < numWatchers ; i++ )
    new Watcher();
    p.add( watcher );
    p.add( new Label( "Access Count" ) );
    p.add( aCount );
    cp.add( p );
    public static void main( String[] args ) {
    Using_vol applet = new Using_vol();
    applet.numCounters = 2; // number of TwoCounter threads
    applet.numWatchers = 2; // number of Watcher threads : watch TwoCounter
    // bigger so that spy more
              JFrame frame = new JFrame( "synchronize Vs volatile" );
              frame.setDefaultCloseOperation( javax.swing.JFrame.EXIT_ON_CLOSE );
              frame.getContentPane().add( applet );
              frame.setSize( 450, applet.numCounters * 50 + 50 );
              applet.init();
              applet.start();
    frame.setVisible( true );

  • Using a variable in two threads...

    i am new to java and have a thread question.
    i am using a GUI and then run a swingworker thread to get updates from a server on a regular basis.
    i realize that if the GUI is updated within the swingworker thread i need to use the invokeLater to put it on the EDT.
    but what if i have a boolean variable declared in the main class that i use within the swingworker thread.
    in other words both the EDT and the swingworker thread might use or set the variable.
    does this variable need to be declared in any special way?
    boolean isOn = false; (how i am declaring)
    so one case would be where the EDT sets the variable true or false and the swingworker thread simply checks the state of the variable.
    if (isOn) (do this);
    else (do that);
    in another case both the EDT and the swingthread check and set the var.
    if (isOn) { Thread.sleep(10);}
    isOn = true;
    isOn = false;
    im new to java so just trying to see if this is ok and if i need to declare isOn as syncronized or something.
    not sure if this will work

    There's no need to use both volatile and
    synchronized. Either declare the variable as volatile
    (*), or use synchronization when reading/writing it.
    (*) At least in theory, I'm not sure this has ever
    been guaranteed to work in practice. In any case,
    volatile is superfluous if you use synchronization.You need to use volatile keyword if do not want that compiler optimizes
    you code in multithread applications.
    For example:
        private boolean isDataChanged;
        void setDataChanged(boolean dataChanged){ isDataChanged = dataChanged; }
        boolean isDataChanged(){ return isDataChanged; }
        void someMethod(){
         isDataChanged = false;
         // some code which does not change isDataChanged variable
         if(isDataChanged){
             // code block 1
         }else{
             // code block 2
        }Compiler can optimize someMethod method to the next code because
    isDataChanged is false in if-else statement:
        void someMethod(){
         isDataChanged = false;
         // some code which does not change isDataChanged variable
         // code block 2
        }But isDataChanged viariable can be changed by another thread
    in multifreads applications so optimization will not be correctly
    because isDataChanged can be true in if-else statement.

  • VM experts, please resolve dispute re

    Over in "Advanced Topics",
    http://forum.java.sun.com/thread.jsp?forum=4&thread=167222
    dnoyeB and I are having a spirited discussion about the mechanics of thread working copies vs. main mem's master copy. It's a very long discussion that spawned off from somebody else's simple question "When do you use volatile vs. synchronized." Our disagreement doesn't start until about message 30 or 40, but here are the main points of contention:
    * dnoyeB says that a thread's working copy of a variable is by necessity on the stack, and that therefore, every time a method exits, that thread's working copies (or at least those used by the method) are flushed back to the master copy.
    * I claim that this is not the case, and that one legal model is for a thread's working copy to be in a CPU's cache. I think that dnoyeB's model is unwieldy at best, and not doable at worst.
    * I claim that a thread can directly access variables on the heap.
    * dnoyeB claims that a thread cannot access the heap directly and must alway access variables via the stack.
    Chapter 3 of the VM spec and Chapter 17 of the JLS are involved heavily in this discussion.
    Please set us straight. :-)
    Thanks,
    Jeff

    I am beginning to think we were both right and wrong.I disagree. See below for why.
    1. the only thread local copies of variables are in
    the operand stack, not in a frame. This is still the
    stack so method ending does flush the stack var.I am using the terminology from the JVM spec and Venners' book. When I said operand stack and thread stack I meant essentially the same thing.
    void func()
    obj.x +=2;
    obj.x +=2;
    }according to the spec
    if x is not volatile, after the first add, x is still
    on the operand stack, and can be used directly from
    the operand stack. If x were volatile, it would have
    to be written back to main mem after the first write,
    and reloaded for the second.You are completely wrong. You are equating memory used for holding the stack frames (which holds: local vars, operand stack, and frame data) with thread-local memory view. obj.x can live in this thread's local memory (which holds: class and instance fields, array elements that are used by methods in this thread; they live there in-between method calls, if you want).
    What you seem to be saying is that if you have a method implemented as
    int getX ()
        return obj.x;
    }then [in your opinion] this method will automatically return the most-up-to-date, out-of-main memory value of obj.x even if x is not volatile?
    If x were volatile, it would have
    to be written back to main mem after the first write,
    and reloaded for the second.In other words, you are saying that in the scenario
    thread 1                                     thread 2
    getX();                                      ...
    ...                                             obj.x = new_value
    getX();                                      ...         the second getX() by thread 1 is guaranteed to see the new_value for obj.x even if it is not volatile, just because the operand value had to be popped off the operand stack in between the calls to getX()?
    This is clearly incorrect. As has been stated several times already, you are incorrectly assuming that method boundaries act as memory barriers in the JMM sense. They do not.
    You trying to imply that the acts of pushing and popping values to/from the operand stack are the actual events of reconciling thread-local memory with main memory. This is incorrect. If Java bytecode was designed around the usual register-only abstract architecture then where would you be? There would be no stack frames but there would still be a need for a memory reconciliation model across threads/CPUs.
    Why can't you acknowledge than a thread-local memory can actually map onto the CPU's local memory and Java is the first common programming language that attempted to define a memory coherency model for a concurrent runtime? All other langugages silently assume that you inherit the memory model from the underlying hardware.
    Vlad.

  • Double Factory pattern purposal as replacement for Double Check #2

    Hi All,
    Here is the code for the pattern proposal, its intended as a replacement for double checked locking, which was proved to be broken in 2001. Here is the code...
    public class DoubleFactory {
       private static Object second_reference = null;
       public static Object getInstance() {
          Object toRet = second_reference;
             if (toRet == null) {
                second_reference = CreationFactory.createInstance();
                toRet = second_reference;
          return toRet;
       private DoubleFactory() {}
    public class CreationFactory {
       private static Object instance = null;
       public static synchronized Object createInstance() {
          if (instance == null) {
             instance = new Object();
          return instance;
      }Also I have spent several months discussing this with Peter Haggar, who believes that this code is not guaranteed to work. However I have been unable to discern from his message why he believes this will not be guaranteed to work, and I am posting this here to attempt to find a clearer explanation or confirmation that the pattern I am purposing (Double Factory) is guaranteed to work.
    Thanks,
    Scott
    ---------------------------- Original Message ----------------------------
    Subject: Re: [Fwd: Double Factory replacement for Double Check #2] From:
    "Scott Morgan" <[email protected]>
    Date: Fri, January 25, 2008 10:36 pm
    To: "Peter Haggar" <[email protected]>
    Hi Peter,
    I appologize if my last response came accross as rude or something. If
    my code is not guaranteed to work ok, can you help me understand why. I
    am after all looking for a solution for all of us.
    If my solution is wrong as you say because the member variables of the
    singleton are not up to date. I understand this to mean that the
    second_reference pointer is assigned to the memory where the instance
    object will get created before the instance object even starts the
    creation process (when the jvm allocates memory and then enters the
    constructor method of the Singleton). This doesn't seem possible to me.
    Can you refrase your statments, to help me understand your points?
    If not I am happy to turn to the original wiki for discussion.
    Thanks for your effort,
    Scott
    Thanks for asking my opinion, many times, then telling me I'm
    wrong...wonderful. You are a piece of work my friend. For what it'sworth, your email below shows you still don't understand these issues
    or what I was saying in my emails. I've been more than patient.
    >
    All the best. And by the way, your code is not guaranteed to work. It's not just me that's "wrong", it's also the engineers at Sun who
    designed Java, the JVM, and the memory model, and countless people who
    have studied it. I'm glad you have it all figured out.
    >
    Peter
    "Scott Morgan" <[email protected]>
    01/18/2008 12:47 PM
    Please respond to
    [email protected]
    To
    Peter Haggar/Raleigh/IBM@IBMUS
    cc
    Subject
    Re: [Fwd: Double Factory replacement for Double Check #2]
    Hi Peter,
    Thanks I understand your position now. However am I still believe that
    it will work and be safe;
    1) the Singleton you show would be fully constructed (having exited theSingleton() method) before the createInstance() method would have
    returned.
    2) The second_reference could not be assigned until the createInstance()
    method returns.
    3) So by the time second_reference points to Singleton all of the valueswill be set.
    >
    >
    I do understand that if the createInstance method was not synchronized(at the CreationFactory class level) that my logic would be flawed, but
    since there is synchronization on that method these points are true, and
    your comments about up-to-date values are not accurate.
    >
    Cheers,
    Scott
    >In your listing from your latest email T2 does encounter a sync block
    on createInstance.
    >>>>
    No. T2 will call getInstance and see second_reference as non-null.second_reference was made non-null by T1.
    >>
    >>>>
    What are you exactly are you refering to with the phrase 'up-to-datevalues'?
    >>>>
    Assume my singleton ctor is thus:
    public class Singleton
    private int i;
    private long l;
    private String str;
    public Singleton()
    i = 5;
    l = 10;
    str = "Hello";
    T2 will get a reference to the Singleton object. However, because youaccess second_reference without synchronization it may not see i as 5,
    l as 10 and str as "Hello". It may see any of them as 0 or null. This
    is not the out of order write problem, but is a general visibility
    problem because you are accessing a variable without proper
    synchronization.
    >>
    Peter
    "Scott Morgan" <[email protected]>
    01/16/2008 11:38 PM
    Please respond to
    [email protected]
    To
    Peter Haggar/Raleigh/IBM@IBMUS
    cc
    Subject
    Re: [Fwd: Double Factory replacement for Double Check #2]
    Hi Peter,
    In your listing from your latest email T2 does encounter a sync blockon createInstance.
    >>
    What are you exactly are you refering to with the phrase 'up-to-datevalues'?
    In this code the Singleton should also be
    A) non mutable (as in the instance of class Object in the example).
    If the singleton was more complex then the code to populate it'svalues
    would go inside the sync of createInstance().
    B) mutable with synchronization on it's mutator methods.
    In your article you mention out of order writes, which doesn't occurin
    this code.
    Cheers,
    Scott
    You read it wrong.
    - T1 calls getInstance which in turn calls createInstance.
    - T1 constructs the singleton in createInstance and returns to
    getInstance.
    - T1 sets second_reference to the singleton returned in getInstance. -T1 goes about its business.
    - T2 calls createInstance.
    - T2 sees second_reference as non-null and returns it
    - Since T2 accessed second_reference without sync, there is noguarantee
    that T2 will see the up-to-date values for what this object refers to.
    - Therefore the code is not guaranteed to work.
    >>>
    If this is not clear:
    - Re-read my email below
    - Re-read my article
    - If still not clear, google on Double Checked Locking and readanything
    from Brian Goetz or Bill Pugh.
    Peter
    "Scott Morgan" <[email protected]>
    01/13/2008 05:26 AM
    Please respond to
    [email protected]
    To
    Peter Haggar/Raleigh/IBM@IBMUS
    cc
    Subject
    Re: [Fwd: Double Factory replacement for Double Check #2]
    Hi Peter,
    Thanks for the reply, I don't see how T2 would see the a referenceto
    a
    partialy initialized object before the createInstance() method had
    returned. If T1 was in createInstance() when T2 entered
    getInstance(), T2 would wait on the CreationFactory's class monitor to
    wait to enter createInstance().
    Or in other words in the line of code ....
    second_reference = CreationFactory.createInstance();
    The pointer second_reference couldn't be assigned to the singleton
    instance when the synchronized createInstance() had fully constructed,initialized and returned the singleton instance. Before that the the
    second_reference pointer would always be assigned to null. So any
    thread entering getInstance() before createInstance() had returned
    (for the first time) would wait on the CreationFactory's class monitor
    and enter the createInstance() method.
    >>>
    So T2 will wait for T1.
    Cheers,
    Scott
    PS I think I am writing requirements for my next project :)
    Sorry for the delay...been in all day meetings this week.
    You are correct...I had been reading your code wrong, my apologies.
    My explanations, although correct, did not exactly correspond to your
    code.
    However, the code is still not guaranteed to work. Here's why:
    Assume T1 calls getInstance() which calls createInstance() and returnsthe
    singelton. It then sets second_reference to refer to that singleton.
    So
    far, so good. Now, T2 executes and calls getInstance(). It can see
    second_reference as non-null, so it simply returns it. But, there
    was
    no
    synchronization in T2's code path. So there's no guarantee that even
    if
    T2 sees an up-to-date value for the reference, that it will seeup-to-date
    values for anything else, ie what the object refers to...it's
    instance data. If T2 used synchronization, it would ensure that it
    read
    up-to-date
    values when it obtained the lock. Because it didn't, it could see
    stale
    values for the object's fields, which means it could see a partially
    constructed object.
    >>>>
    In the typical double-checked locking, the mistake is to assume theworst
    case is that two threads could race to initialize the object. But
    the worst case is actually far worse -- that a thread uses an object
    which
    it
    believes to be "fully baked" but which is in fact not.
    Peter
    "Scott Morgan" <[email protected]>
    01/03/2008 06:33 PM
    Please respond to
    [email protected]
    To
    Peter Haggar/Raleigh/IBM@IBMUS
    cc
    Subject
    Re: [Fwd: Double Factory replacement for Double Check #2]
    Hi Peter,
    Thanks for responding, I am still thinking that your mis
    interpreting
    the code so I have rewritten it here (Replacing
    DoubleFactory.instance with DoubleFactory.second_reference for
    clarity). If the T1 burps (gets interrupted) in the createInstance
    method it wouldn't have returned so the second_reference pointer
    would have never been
    assigned
    so T2 would just try again upon entering the getInstance method. Orif
    it had already entered getInstance it would be waiting to enter
    (until T1 releases the lock on CreationFactory.class ) on the
    createInstance method.
    >>>>
    public class DoubleFactory {
    private static Object second_reference = null;
    public static Object getInstance() {
    Object toRet = second_reference;
    if (toRet == null) {
    second_reference =
    CreationFactory.createInstance();
    toRet = second_reference;
    return toRet;
    private DoubleFactory() {}
    public class CreationFactory {
    private static Object instance = null;
    public static synchronized Object createInstance() {
    if (instance == null) {
    instance = new Object();
    return instance;
    Does this clear up my idea at all?
    second_reference should be always pointing to
    null
    or
    a fully initialized Object
    (also referenced by the pointer named 'instance' ), I don't see howit would end up partially initialized.
    >>>>
    Thanks Again,
    Scott
    "It" refers to T2.
    Your createInstance method is identical to my Listing 2 and is fine
    and
    will work.
    Yes, the problem with your code is in getInstance.
    >I don't see how the DoubleFactory getInstance method could bereturning
    a partially initialized object at this point. If CreationFactoryalways
    returns a fully initialized object and DoubleFactory only assigns a
    new
    reference/pointer to it how could DoubleFactory getInstance return a
    reference/pointer to partially initialized object?
    >>>>>>>
    >>>>>
    The reason it is not guaranteed to work is explained in my previousemails
    and in detail in the article. However, I'll try again. Anytime you
    access shared variables from multiple threads without proper
    synchronization, your code is not guaranteed to work. Threads are
    allowed
    to keep private working memory separate from main memory. There are
    2
    distinct points where private working memory is reconciled with main
    memory:
    - When using a synchronized method or block - on acquisition of thelock
    and when it is released.
    - If the variable is declared volatile - on each read or write of
    that
    volatile variable. (Note, this was broken in pre 1.5 JVMs which isthe
    reason for the caveat I previously mentioned)
    Your createInstance method uses synchronization, therefore, the
    reconciliation happens on lock acquisition and lock release. T1 can
    acquire the lock in createInstance, make some updates (ie create an
    object, run it's ctor etc), but then get interrupted before exiting
    createInstance and therefore before releasing the lock. Therefore,
    T1
    has
    not released the lock and reconciled its private working memory withmain
    memory. Therefore, you have ZERO guarantee about the state of mainmemory
    from another threads perspective. Now, T2 comes along and accesses
    "instance" from main memory in your getInstance method. What will
    T2
    see?
    Since it is not properly synchronized, you cannot guarantee that T2sees
    the values that T1 is working with since T1 may not have completely
    flushed its private working memory back to main memory. Maybe it
    did completely flush it, maybe it didn't. Since T1 still hold the
    lock,
    you
    cannot guarantee what has transpired. Maybe your JVM is not usingprivate
    working memory. However, maybe the JVM your code runs on does or
    will
    some day.
    Bottom line: Your code is not properly synchronized and is notguaranteed
    to work. I hope this helps.
    Peter
    "Scott Morgan" <[email protected]>
    01/03/2008 12:49 PM
    Please respond to
    [email protected]
    To
    Peter Haggar/Raleigh/IBM@IBMUS
    cc
    Subject
    Re: [Fwd: Double Factory replacement for Double Check #2]
    Hi Peter,
    Thanks for your response, I don't follow what 'it' refers to in
    the
    phrase 'It can see'. So for the same reason that you state that
    example 2 from your article I believe this class CreationFactory to
    work flawlessly when a client object calls the createInstance
    method.
    >>>>>
    I see this CreationFactory code as identical to your example 2 doyou agree with this?
    >>>>>
    public class CreationFactory {
    private static Object instance = null;
    public static synchronized Object createInstance() {
    if (instance == null) {
    instance = new Object();
    return instance;
    }Then my rational in the DoubleFactory class is that it can obtain a
    reference/pointer to the fully initialized object returned bycalling the above code. I believe you think that the problem with
    my code is
    in
    the DoubleFactorys getInstance method, is this correct?
    I don't see how the DoubleFactory getInstance method could bereturning
    a partially initialized object at this point. If CreationFactory
    always
    returns a fully initialized object and DoubleFactory only assigns a
    new
    reference/pointer to it how could DoubleFactory getInstance return a
    reference/pointer to partially initialized object?
    >>>>>
    Thanks again,
    Scott
    public static synchronized Singleton getInstance() //0
    if (instance == null) //1
    instance = new Singleton(); //2
    return instance; //3
    This above code is fine and will work flawlessly.
    Annotating my paragraph:
    T1 calls getInstance() and obtains the class lock at //0. T1 "sees"
    instance as null at //1 and therefore executes: instance = new
    Singleton() at //2. Now, instance = new Singleton() is made up of
    several lines of non-atomic code. Therefore, T1 could be
    interrupted
    after Singleton is created but before Singleton's ctor isrun...somewhere
    before all of //2 completes. T1 could also be interrupted after
    //2 completes, but before exiting the method at //3. Since T1 has
    not
    exited
    its synchronized block it has not flushed its cache. Now assume T2
    then
    calls getInstance().
    All still true to this point. However, with your code the nextparagraph
    is possible, with the code above, it's not. The reason is that T2
    would
    never enter getInstance() above at //0 because T1 holds the lock. T2will
    block until T1 exits and flushes it's cache. Therefore, the code
    above
    is
    properly thread safe.
    It can "see" instance to be non-null and thus
    return it. It will return a valid object, but one in which its ctor
    has
    not yet run or an object whose
    values have not all been fully flushed since T1 has not exited itssync
    block.
    "Scott Morgan" <[email protected]>
    01/02/2008 06:10 PM
    Please respond to
    [email protected]
    To
    Peter Haggar/Raleigh/IBM@IBMUS
    cc
    Subject
    Re: [Fwd: Double Factory replacement for Double Check #2]
    Hi Peter,
    Thanks for the response I understand the rational for inventing
    the
    double check anti pattern, I am sorry I still don't understand the
    difference between your solution #2 and my CreationFactory class.
    >>>>>>
    From your article figure 2.public static synchronized Singleton getInstance() //0
    if (instance == null) //1
    instance = new Singleton(); //2
    return instance; //3
    If I understand your email correctly this figure 2 is also flawed,since...
    >>>>>>
    T1 calls getInstance() and obtains the class lock at //0. T1 "sees"
    instance as null at //1 and therefore executes: instance = new
    Singleton() at //2. Now, instance = new Singleton() is made up ofseveral lines of non-atomic code. Therefore, T1 could be
    interrupted
    after Singleton is created but before Singleton's ctor isrun...somewhere
    before all of //2 completes. T1 could also be interrupted after
    //2 completes, but before exiting the method at //3. Since T1 has
    not
    exited
    its synchronized block it has not flushed its cache. Now assume T2
    then
    calls getInstance(). It can "see" instance to be non-null and thus
    return it. It will return a valid object, but one in which its
    ctor
    has
    not yet run or an object whose
    values have not all been fully flushed since T1 has not exited itssync
    block.
    So is #2 is also flawed for this reason?
    If so please revise your article, since I interpreted #2 as a
    plausible
    solution recommended by you (which lead me to the DoubleFactory
    idea).
    If not please help me understand the difference between #2 and my
    CreationFactory class.
    >>>>>>
    Thanks,
    Scott
    #2 is in Listing 2 in the article. What I meant was to forget the
    DCL
    idiom, and just synchronize the method...that's what listing 2
    shows.
    DCL
    was invented to attempt to get rid of the synchronization for 99.9%
    of
    the
    accesses.
    The solution I outlined in my email is using the DCL idiom, but on
    a
    1.5
    or later JVM and using volatile.
    You solution is not guaranteed to work. Here's why:
    public class DoubleFactory {
    private static Object instance = null;
    public static Object getInstance() {
    Object toRet = instance;
    if (toRet == null) {
    instance =
    CreationFactory.createInstance();
    toRet = instance;
    return toRet;
    private DoubleFactory() {}
    public class CreationFactory {
    private static Object instance = null;
    public static synchronized ObjectcreateInstance()
    //1
    if (instance == null) {
    instance = new Object(); //2
    return instance;
    } //3
    }T1 calls createInstance() and obtains the class lock at //1. T1"sees"
    instance as null and therefore executes: instance = new Object() at//2.
    Now, instance = new Object() is made up of several lines of
    non-atomic
    code. Therefore, T1 could be interrupted after Object is created
    but
    before Object's ctor is run...somewhere before all of //2
    completes.
    T1
    could also be interrupted after //2 completes, but before exiting
    the
    method at //3. Since T1 has not exited its synchronized block ithas
    not
    flushed its cache. Now assume T2 then calls getInstance(). It can"see"
    instance to be non-null and thus return it. It will return a
    valid object, but one in which its ctor has not yet run or an
    object
    whose
    values have not all been fully flushed since T1 has not exited itssync
    block.
    The bottom line is that if you are accessing shared variables
    between
    multiple threads without proper protection, you are open for aproblem.
    Proper protection is defined as: proper synchronization pre 1.5,
    and
    proper synchronization or proper use of volatile 1.5 or after.
    Therefore, if you must use the DCL idiom you have one option: -
    Use DCL with volatile on a 1.5 or later JVM.
    >>>>>>>
    You can also forget about DCL and just use synchronization (listing2
    in
    my article) or use a static field (listing 10 in my article).
    I hope this clears it up.
    Peter
    "Scott Morgan" <[email protected]>
    01/02/2008 04:00 PM
    Please respond to
    [email protected]
    To
    Peter Haggar/Raleigh/IBM@IBMUS
    cc
    Subject
    Re: [Fwd: Double Factory replacement for Double Check #2]
    Hi Peter,
    I apologies for not understanding but I don't see what is
    different
    between the solution you purposed...
    2) Don't use DCL but use synchronization
    and the code that I am putting forward. Perhaps I do just notunderstand
    but you seem to be contradicting yourself in this email?
    I understand that you are saying in #2 that this will always 'work'
    with
    out any issues...
    public static Object instance = null;
    public static synchronized Object getInstance() {
    if (instance == null) {
    instance = new Object();
    return instance;
    But first you seem to say in the email that if T1 gets
    interrupted
    it
    may leave the instance pointing to a partially initialized object?
    So as far as I understand it the createInstance method in my
    CreationFactory class should be successful (always retuning a
    fully initialized object) for the same reason #2 is successful.
    Please keep in mind that there are two different instancepointers
    in
    the code I sent you, one is part of the DoubleFactory class and
    the other is part of the CreationFactory class.
    >>>>>>>
    Thanks for your time, just looking for better solutions!
    Scott
    Scott,
    Your solution is not guaranteed to work for various reasons
    outlined
    in
    the article. For example, you can still return from your code apartially
    initialized object. This can occur if T1 gets interrupted beforeleaving
    the synchronized method createInstance() and T2 calls
    getInstance().
    T2
    can "see" toRet/instance as non-null but partially initialized
    since
    T1
    has not fully flushed its values.
    As of 1.5, Sun fixed various issues with the memory model that
    were
    broken. Double Checked Locking will still break unless you usevolatile
    (which was fixed in 1.5). Therefore, the following code works:
    volatile Helper helper;
    Helper getHelper() {
    if (helper == null)
    synchronized(this) {
    if (helper == null)
    helper = new Helper();
    return helper;
    but the original DCL idiom will not work. So, your options are:
    1) Use DCL with volatile (above)
    2) Don't use DCL but use synchronization
    3) Don't use DCL, but use a static field.
    #2 and #3 are outlined in my article from 2002.
    Hope this helps,
    Peter
    "Scott Morgan" <[email protected]>
    12/26/2007 04:12 PM
    Please respond to
    [email protected]
    To
    Peter Haggar/Raleigh/IBM@IBMUS
    cc
    Subject
    [Fwd: Double Factory replacement for Double Check #2]
    Hi Peter,
    Thanks for the article on the out of order write problem. Whatdo
    you
    think of this as a solution?
    TIA,
    Scott
    ---------------------------- Original Message----------------------------
    Subject: Double Factory replacement for Double Check #2
    From: "Scott Morgan" <[email protected]>
    Date: Wed, December 26, 2007 2:55 pm
    To: [email protected]
    Hi Ward,
    Here is a pattern submission
    Double Factory
    Lazy initialization of singletons in accepted for a while usingthe
    double check pattern. However it has been discovered that the
    double
    check pattern isn't thread safe because of the out of order write
    problem. This problem occurs when Threads entering the Singleton
    Factory method return with a fully constructed, but partially
    initialized, Singleton object.
    >>>>>>>>
    Therefore: It makes sense to look for a way to initializeSingletons
    in
    a Lazy and Thread Safe manor. The following illustrates a fairly
    simple
    solution...
    package foo;
    public class DoubleFactory {
    private static Object instance = null;
    public static Object getInstance() {
    Object toRet = instance;
    if (toRet == null) {
    instance =
    CreationFactory.createInstance();
    toRet = instance;
    return toRet;
    private DoubleFactory() {}
    public class CreationFactory {
    private static Object instance = null;
    public static synchronized ObjectcreateInstance()
    if (instance == null) {
    instance = new Object();
    return instance;
    This gets around the out of order write problem because all
    Threads
    waiting on the CreationFactory's Class monitor will have a fully
    constructed and initialized instance when they actually exit the
    createInstance method.
    >>>>>>>>
    >>>>>>>>
    During runtime while the Singleton instance is getting created(constructed and initialized) there may be a few Threads waiting
    on
    the
    CreationFactory Class's objects monitor. After that period all
    the
    Treads
    accessing
    the Singleton will have unsynchronized reads to the instance,
    which
    will
    optimize execution.
    References:
    http://www.ibm.com/developerworks/java/library/j-dcl.html
    Copyright 2007 Adligo Inc.

    Scott-Morgan wrote:
    Hi All,
    Thanks for your comments, here are some more....
    jtahlborn you state that
    the only way to guarantee that a (non-final) reference assignment is visible across threads is through the use of volatile and synchronized,
    From the jvm spec
    http://java.sun.com/docs/books/jls/third_edition/html/memory.html
    17.4.1 Shared Variables
    Memory that can be shared between threads is called shared memory or heap memory.
    All instance fields, static fields and array elements are stored in heap memory.
    Since both the second_reference and instance fields are both static, they are shared and visible across all threads.Yes, all these things are shared across threads, however, if you keep reading, there is a notion of "correct" sharing. obviously these values may be visible, that's why double-checked locking was used for so long before people realized it was broken. it worked most of the time, except when it didn't, and that's what i'm trying to show. that the only way to correctly share state between threads is via synchronization points, the most common being volatile and synchronized (there are a couple of other less used ones which don't apply here). The articles you linked to below from ibm cover the "visibility" in great depth, this is exactly what i am referring to.
    You also state that volatile is a solution, but you seem to rebut your self in stating that the overhead for volatile is almost as great as synchronization.
    This article illustrates the solution, and also comments on the overhead of volatile.
    http://www.ibm.com/developerworks/library/j-jtp03304/
    linked from
    http://www.ibm.com/developerworks/java/library/j-dcl.html
    volatile is a solution, in that it is correct, and you avoid the appearance of synchronization each time. however, since the semantics of volatile were strengthened in the new memory model, using volatile will perform practically (if not exactly) the same as simply synchronizing each time. the article you link to says exactly this under the heading "Does this fix the double-checked locking problem?".
    Also could you be more specific about the example at the end of the jvm memory spec page, like a section number?It's the very last thing on the page, the "discussion" under 17.9, where it mentions that changes to "this.done" made by other threads may never be visible to the current thread.

  • Thread-safe Singleton

    Hi,
    I want to create a thread safe singleton class. But dont want to use the synchronized method or block. One way i could think of was initializing the object in static block. This way the instance will be created only once. But what if instance becomes null after some time. How will it get initialized again. Can anyone help me in creating a thread safe singleton class.
    Also i would really really appreciate if some one can point me to a good tutorial on design patters, I searched on google.. Found many.. But not finding any of them satisfying.
    Thanks

    tschodt wrote:
    Balu_ch wrote:
    kilyas wrote:
    Look into the use of volatile instead of synchronized, however the cost of using volatile is comparable to that of synchronizingCan you please explain in detail Google can.
    Google ( [java volatile vs synchronized|http://www.google.com/search?q=java+volatile+vs+synchronized] ).
    Hi, I think we need to use both (volatile and synchronized). Can some please explain how "volatile" alone can be used to ensure thread safe singleton? Below is the code taken from wikipedia
    public class Singleton {
       // volatile is needed so that multiple thread can reconcile the instance
       // semantics for volatile changed in Java 5.
       private volatile static Singleton singleton;
       private Singleton()
       // synchronized keyword has been removed from here
       public static Singleton getSingleton(){
         // needed because once there is singleton available no need to acquire
         // monitor again & again as it is costly
         if(singleton==null) {
           synchronized(Singleton.class){
              // this is needed if two threads are waiting at the monitor at the
              // time when singleton was getting instantiated
              if(singleton==null)
              singleton= new Singleton();
       return singleton;
    }

  • Collection concurreny issue

    Hi
    I have an issue with probably concurrency. Look at the code below:
    import java.util.HashMap;
    import java.util.LinkedList;
    public class TestStressMarketPriceUpdateProcessor {
      ObjectQueue objectQueue = new ObjectQueue();
      UpdateProcessor uP;
      class UpdateProcessor extends Thread {
        UpdateProcessor() {
          super("UpdateProcessor");
        public void run() {
          while (true) {
            Object o = objectQueue.getLastObject();
      class Updater extends Thread {
        Object lock = new Object();
        String num;
        public Updater(int num) {
          super("Updater " + num);
          this.num = String.valueOf(num);
        public void run() {
          while (true) {
            synchronized (lock) {
              try {
                lock.wait(1);
              } catch (InterruptedException e) {
                e.printStackTrace();
            objectQueue.putObject(new Object(), num);
      public class ObjectQueue {
        HashMap<String, Object> map;
        LinkedList<Object> list;
        Object lock;
        public ObjectQueue() {
          map = new HashMap<String, Object>(60, 0.9f);
          list = new LinkedList<Object>();
          lock = new Object();
        public void putObject(Object obj, String key) {
          synchronized (lock) {
            Object prevObj = map.get(key);
            list.remove(prevObj);
            map.put(key, obj);
            list.add(obj);
            lock.notify();
        public Object getLastObject() {
          synchronized (lock) {
            if (list.isEmpty()) {
              try {
                lock.wait();
              } catch (InterruptedException ex) {
                return null;
            Object lastObject = list.removeFirst();
            map.values().remove(lastObject);
            return lastObject;
      public TestStressUpdateProcessor() {
        uP = new UpdateProcessor();
        uP.start();
        int num = 50;
        for (int i = 0; i < num; i++) {
          (new Updater(i)).start();
      public final static void main(String args[]) {
        new TestStressUpdateProcessor();
    }What i experience is that sometimes the removeFirst() method throws a NoSuchElementException.
    In the first place i cant see how could that happen, since only synchronized block can remove elements in the code.
    I also suspected memory concurrency issue, but no matter volatile, or synchronized List, the issue still happens sometimes.
    Can anyone help show my whats the flaw in the code?
    thanx
    david

    matra,
    As I can see from you code, there is a main thread (TestStressMarketPriceUpdateProcessor) which tries continously to get object from the ObjectQueue
    the ObjectQueue is another thread which is very fine.
    There is another thread which is an updater thread. This thread populate the ObjectQueue.
    All of the above leads up to a common resource which is ObjectQueue
    The updater wait is too short which make the ObjectQueue always get populated and does not allow ObjectQueue to wait some time so I would do the following to the code ; I am not going to explain the changes; however, you can look and notice the changes by your self.
    Please notice the while loop in the method getLastObject()
    public class TestStressMarketPriceUpdateProcessor {
      ObjectQueue objectQueue = new ObjectQueue();
      UpdateProcessor uP;
      UpdateProcessor uP2;
      class UpdateProcessor extends Thread {
        UpdateProcessor(int updaterNum) {
          super("UpdateProcessor" + updaterNum);
        public void run() {
          while (true) {
                 * No need to synchronize the  objectQueue
                 * since the  objectQueue.getLastObject() is synchronized
               //synchronized(objectQueue) {
                    Object o = objectQueue.getLastObject();
      } // UpdateProcessor
      class Updater extends Thread {
        String num;
        public Updater(int num) {
          super("Updater " + num);
          System.out.println("Updater-->" + num);
          this.num = String.valueOf(num);
        public void run() {
          while (true) {
            synchronized (objectQueue) {
              try {
                  objectQueue.wait(1000); // give a chanc to wait sometime
                   objectQueue.putObject(new Object(),num);
                   objectQueue.notify();
              } catch (InterruptedException e) {
                e.printStackTrace();
      } // Updater
      public class ObjectQueue {
        HashMap<String, Object> map;
        LinkedList<Object> list;
        public ObjectQueue() {
          map = new HashMap<String, Object>(60, 0.9f);
          list = new LinkedList<Object>();
        public void putObject(Object obj, String key) {
          synchronized (this) {
            Object prevObj = map.get(key);
            list.remove(prevObj);
            map.put(key, obj);
            list.add(obj);
        public Object getLastObject() {
          synchronized (this) {
             while(list.isEmpty())  {
                  System.out.println("I am empty I will wait....;Thread-->" + Thread.currentThread().getName());
              try {
                this.wait();
                System.out.println("wake up to check if I am empty");
              } catch (InterruptedException ex) {
                   // Restore the interrupted status
                  Thread.currentThread().interrupt();
             System.out.println("I am NOT empty....;Thread-->" + Thread.currentThread().getName());
             System.out.println("list size before-->" + map.size());
             Object lastObject = list.removeFirst();
            map.values().remove(lastObject);
            System.out.println("list size after-->" +list.size());
            return lastObject;
      public TestStressMarketPriceUpdateProcessor() {
        uP = new UpdateProcessor(1);
        uP.start();
        uP2 = new UpdateProcessor(2);
        uP2.start();
        int num = 5; // give a chance to see empty list
        for (int i = 0; i < num; i++) {
          new Updater(i).start();
      public final static void main(String args[]) {
        new TestStressMarketPriceUpdateProcessor();
    }Regards,
    Alan Mehio
    London, UK

  • Is volatile necessary for variables only accessed inside synchronized block

    Hi,
    I am using ExecutorService to execute a set of threads. Then the calling thread needs to wait until all of them are done to reuse the thread pool to run another set of threads (so I can't use the ExecutorService.shutdown() to wait for all of the threads at this point). So I write a simple monitor as below to coordinate the threads.
    My question is: will it work? someone suggests that it might not work because it will busy spin on the non-volatile int which may or may not be updated with the current value from another thread depending on the whims of the JVM. But I believe that variables accessed inside synchronized blocks should always be current. Can anyone please help me to clarify this? Really appreciate it.
         * Simple synchronization class to allow a thread to wait until a set of threads are done.
         class ThreadCoordinator{
         private int totalActive = 0;
         public synchronized void increment(){
         totalActive++;
         notifyAll();
         public synchronized void decrement(){
         totalActive--;
         notifyAll();
         public synchronized void waitForAll(){
         while(totalActive != 0){
         try{
         wait();
         }catch (InterruptedException e){
         //ignore
         }

    Don't do that. Just save the Futures returned by the ExecutorService, and call get() on them all. This will only return when all the tasks have finished.

  • Synchronized - volatile

    Can somebody confirm following thought.
    int count;
    synchronized (this) {
        ++count;
    } is safer then volatile int count;
    ++count;Iunderstand that probability of having trouble with volatile version is extremely small. But am I correct when saying that this probabily is not zero. If I'm right, is ther any usage for volatile variables in "production" software which can not fail.

    The synchronized code is correct because it makes the read-increment-write operation appear atomic to other threads. The volatile code is not correct if other threads will access the count variable.
    Iunderstand that probability of having trouble with
    volatile version is extremely small.I don't believe you can make any prediction about the possibility of problems by not properly synchronizing your code. A good guess is that you almost certainly will have a problem with the volatile code.
    But am I correct
    when saying that this probabily is not zero. If I'm
    right, is ther any usage for volatile variables in
    "production" software which can not fail.Yes, there is a usage of volatile that is correct -- if you merely read or write a volatile variable, each thread will see the proper value. You could achieve the same goal by using synchronized code, but you have to remember to put all accesses of the variable in synchronized code, and this implementation may be slower than simply making the variable volatile.

  • Which object's monitor does a synchronized method acquire?

    from the Java Tutorial for concurrency programming:
    " When a thread invokes a synchronized method, it automatically acquires the intrinsic lock _for that method's object_ and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception. "
    what exactly does this mean?
    do synchronized methods acquire the monitors for objects of type: java.lang.reflection.Method
    please consider this code:
    public class Foo {
      private int counter = 0;
      public synchronized void incriment() { counter++; }
      public synchronized void decriment() { counter--; }
    Foo f = new Foo();
    Class[] sig = new Class[0];
    Method m = f.getClass().getMethod("incriment", sig);
    // ok. so "m" is the relevant method object.
    f.incriment(); // <-- is the monitor for "m" ,
                          // or the monitor for "f", acquired?
    .......my reading of the Concurrency Tutorial is that synchronized methods use the monitors of java.lang.reflection.Method objects?
    and thus, Foo is not thread safe, right?
    however, this simple change makes Foo thread-safe?
    public class Foo {
      private volatile int counter = 0; // "volatile"
      public void incriment() { counter++; }
      public void decriment() { counter--; }
    }thanks.
    Edited by: kogose on Feb 23, 2009 7:13 PM

    tensorfield wrote:
    jverd wrote:
    tensorfield wrote:
    kogose wrote:
    what exactly does this mean?It means you're complicating things.
    If a method is synchronized, it is. You don't need to go beyond that. The method is synchronized.Not true. You have to know what it means for a method to be synchronized. Often people come in with the erroneous impression that it somehow prevents you from using or accessing the object in any other thread.It's very simple. If a synchronized method is called at the same time from many threads only one call will be executed at a time. The calls will be lined up and performed one after the other in sequence.
    AND because synchronization is on a per object basis, when one synchronized method is being called from one thread, all synchronized methods of that same object are blocked for calling from other threads.
    Simple as that.No, it's not that simple, and as stated, that is not correct. In particular, you didn't mention that for an instance method, all the various threads have to be trying to call instance methods on the same object in order for execution to be sequential.
    You really can't understand Java's syncing without understanding how it relates to locks, and what it means for a method to be synchronized in terms of which lock it acquires.
    Edited by: jverd on Feb 25, 2009 2:47 PM

  • Use of volatile for variable in jdk 1.6 on Linux platforms

    Hello,
    I run the following code on my computer (dual core). This code just create two threads: one adds one to a value contained in
    an object and the other subbs one to it :
    // File: MultiCore.java
    // Synopsis: At the end of some executions the value of a is not equal
    // to 0 (at laest for one of teh threads) even if we do the
    // same number of ++ and --
    // Java Context: java version "1.6.0_11"
    // Java(TM) SE Runtime Environment (build 1.6.0_11-b03)
    // Java HotSpot(TM) Server VM (build 11.0-b16, mixed mode)
    // Linux Context: Linux 2.6.27-12-generic i686 GNU/Linux
    // Author: L. Philippe
    // Date: 03/10/09
    class MaData {
    public int a;
    public MaData() { a = 0; }
    public synchronized void setA( int val ) { a = val; }
    public synchronized int getA() { return a; }
    class MonThread extends Thread {
    MaData md;
    int nb, nb_iter;
    public MonThread( MaData ref, int rnb )
         md = ref;
         nb = rnb;
         nb_iter = 1000;
    public void run()
         if ( nb == 0 ) {
         for ( int i = 0 ; i < nb_iter ; i++ ) {
              // Increment MaData
              md.setA( md.getA()+1 );
         } else {
         for ( int i = 0 ; i < nb_iter ; i++ ) {
              // Decrement MaData
              md.setA( md.getA()-1 );
         System.out.println( Thread.currentThread().getName() + " a= " + md.a);
    public class MultiCore {
    volatile static MaData md;
    public static void main(String args[])
         try {
         // Data to be shared
         md = new MaData();
         MonThread mt1 = new MonThread( md, 0 );
         MonThread mt2 = new MonThread( md, 1 );
         mt1.start();
         mt2.start();
         mt1.join();
         mt2.join();
         } catch ( Exception ex ) {
         System.out.println( ex );
    This is the result i got:
    Thread-0 a= -734
    Thread-1 a= -801
    This ok for the first one but the second should obviously be 0. For me that mean that the volatile does not work and the threads just access to their cache on different cores. Can someone check that ?
    Thanks,
    Laurent

    Why should the second line obviously be zero?
    I don't think even if you make 'a' volatile that setA(getA() + 1) suddenly becomes atomic, because it becomes:
    int temp = getA();
    // if other thread update a, temp does not get updated
    temp = temp + 1;
    setA(temp);So you'll need a synchronized in/decrement methods on MaData or use an AtomicInteger.

  • JMM: legal to optimize non-volatile flag out of particular loop condition?

    Does Java Memory Model allow JIT compiler to optimize non-volatile flag out of loop conditions in code like as follows...
    class NonVolatileConditionInLoop {
      private int number;
      private boolean writingReady = true; // non-volatile, always handled inside synchronized block
      public synchronized void setNumber(int n) {
        while (!writingReady) { // non-volatile flag in loop condition
          try { wait(); }
          catch (InterruptedException e) { e.printStackTrace(); }
        this.number = n;
        this.writingReady = false;
        notifyAll();
      public synchronized int getNumber() {
        while (writingReady) { // non-volatile flag in loop condition
          try { wait(); }
          catch (InterruptedException e) { e.printStackTrace(); }
        this.writingReady = true;
        notifyAll();
        return number;
    }...so that it will execute like this:
    class NonVolatileConditionInLoopHacked {
      private int number;
      private boolean writingReady = true; // non-volatile, always handled inside synchronized block
      public synchronized void setNumber(int n) {
        if (!writingReady) { // moved out of loop condition
          while (true) {
            try { wait(); }
            catch (InterruptedException e) { e.printStackTrace(); }
        this.number = n;
        this.writingReady = false;
        notifyAll();
      public synchronized int getNumber() {
        if (writingReady) { // moved out of loop condition
          while (true) {
            try { wait(); }
            catch (InterruptedException e) { e.printStackTrace(); }
        this.writingReady = true;
        notifyAll();
        return number;
    This question was recently discussed in [one of threads|http://forums.sun.com/thread.jspa?messageID=11001801#11001801|thread] at New To Java forum.
    My take on it is that optimization like above is legal. From the perspective of single-threaded program, repeated checks for writingReady are redundant because it is not modified within the loop. As far as I understand, unless explicitly forced by volatile modifier (and in our case it is not), optimizing compiler "has a right" to optimize based on single-thread execution assumption.
    Opposite opinion is that JMM prohibits such an optimization because methods containing the loop(s) are synchronized.

    gnat wrote:
    ...so that it will execute like this:
    class NonVolatileConditionInLoopHacked {
    private int number;
    private boolean writingReady = true; // non-volatile, always handled inside synchronized block
    public synchronized void setNumber(int n) {
    if (!writingReady) { // moved out of loop condition
    while (true) {
    try { wait(); }
    catch (InterruptedException e) { e.printStackTrace(); }
    this.number = n;
    this.writingReady = false;
    notifyAll();
    public synchronized int getNumber() {
    if (writingReady) { // moved out of loop condition
    while (true) {
    try { wait(); }
    catch (InterruptedException e) { e.printStackTrace(); }
    this.writingReady = true;
    notifyAll();
    return number;
    This question was recently discussed in [one of threads|http://forums.sun.com/thread.jspa?messageID=11001801#11001801|thread] at New To Java forum.
    My take on it is that optimization like above is legal. From the perspective of single-threaded program, repeated checks for writingReady are redundant because it is not modified within the loop. As far as I understand, unless explicitly forced by volatile modifier (and in our case it is not), optimizing compiler "has a right" to optimize based on single-thread execution assumption.
    Opposite opinion is that JMM prohibits such an optimization because methods containing the loop(s) are synchronized.One of the problems with wait() and your the proposed optimization is that "interrupts and spurious wakeups are possible" from wait() . See [http://java.sun.com/javase/6/docs/api/java/lang/Object.html#wait()] Therefore your wait() would loop without checking if this optimization would occur and a interrupt or spurious wake-up happened. Therefore for this reason I do not believe writingReady would be rolled out of the loop. Also the code isn't even equivalent. Once all the threads wake-up due to the notifyAll() they would spin in the while(true) and wait() again. I don't think the JMM prohibits such an optimization because methods containing the loop(s) are synchronized, but because it contains a wait(). The wait() is kind of a temporary flow control escape out of the loop.
    Example:
    writingReady is true
    Thread A calls getNumber(). It waits().
    Thread B calls setNumber(). It calls notifyAll() and writingReady is now false;
    Thread A wakes up in getNumber() and while(true) loop and waits again(). //Big problem.

  • Synchronizing many reader threads with one writer thread?

    Hi
    I was wondering if there is a way in java to allow different threads to read an object simultaneously however to block them all only when the object is being updated. Here is an example:
    I have the following object which is shared between many Servlet instances:
    public class ActiveFlights
         private final HashMap<String,Flight> flights;
         private final Object lock;
         public ActiveFlights()
              flights = new HashMap<String, Flight>();
              lock = new Object();
         public void updateFlights(ArrayList<FlightData> newFlights)
              synchronized (lock)
                   //some code which updates the HashMap
         public ArrayList<Flight> getSomeFlights()
              ArrayList<Flight> wantedFlights = new ArrayList<Flight>();
              synchronized (lock)
                   //some code which selects flights from the HashMap
              return wantedFlights;
    }Now all the Servlet doGet() functions call the getSomeFlights() method. There is also a Timer object which calls the updateFlights() method once every few minutes.
    I need the synchronized blocks in order that the Timer doesn't try to update my object while it is being read by a Servlet however this is not optimal since it also causes each Servlet doGet() to block the others even though it would be possible for to doGet()'s to read the object simultaneously.
    Is there a better way of doing this?
    Thanks
    Aharon

    It is highly unlikely this is a real performance issue for you. Unless you know this is a bottle neck, you don't need to change your code.
    However, as an exercise, you can just use ConcurentHashMap for lockless Map access. However, there is still a risk of getting a read in the middle of a write.
    Instead you can take a snapshot copy of the Map and use this snapshot for reads. See below.
    In term of coding style;
    - I suggest you use the Map and List interfaces where ever possible.
    - You don't need to create a seperate lock object, the Map will do the same job.
    - Use can create the HashMap on the same line as it is declared removing the need to define a constructor.
    public class ActiveFlights {
         private final Map<String, Flight> flights = new HashMap<String, Flight>();
         private volatile Map<String, Flight> flightCopy = new HashMap<String, Flight>();
         public void updateFlights(List<FlightData> newFlights) {
              //some code which updates the HashMap
              // this takes a snapshot copy of the flights.  Use the copy for reads.
              flightCopy = new HashMap<String, Flight>(flights);
         public List<Flight> getSomeFlights() {
              // take a copy of the reference, neither the reference, nor the map it refers to will change over the life of this method call.
              final Map<String, Flight> flightCopy = this.flightCopy;
              final List<Flight> wantedFlights = new ArrayList<Flight>();
              //some code which selects flightCopy from the HashMap
              return wantedFlights;
    }

Maybe you are looking for

  • Photoshop CS2 RAW (NEF) Issue

    Hi, My RAW (.NEF) files will not open in Photoshop CS2. Everytime I try to open a raw image it says... "Could not complete your request because Photoshop does not recognize this type of file" Don't know what to do. CS2 on OSX 10.5.8 with Nikon D90 ph

  • Java.lang.NoSuchMethodException while using LookupDispatchAction

    hi, I am just a novice java developer, developing an application which requires more than one submit button in a single form, for which i have extended LookupDispatchAction class. However i am unable to fix the error with the message java.lang.NoSuch

  • L440 Clickpad - "Tap to click" function not working in "Trackpoint Only" mode

    On a fresh Window 7 install it is possible to tap-to-click when using the Trackpoint rather than pressing down on the Clickpad (which is *very* noisy compared to the X220/X230 buttons and requires far more force). This is very nice alternative to usi

  • Adding infotype text to a infoset

    Hi - Can anyone provide details on how to add infotype text to an infoset so it can be reported through Ad Hoc query?  For example, if "Maintain text" is used to enter text for an infotype record we would like to report the text using PQAH. Thanks, P

  • Opera misses one option bar.

    Since yesterday opera misses the top bar with the menu's(how is that called). The one where it says "File" and "Extra". I have opera installed from the extra repo, but opera-dev from aur has the same problem. I tried removing .opera/ but that doesn't