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

Similar Messages

  • DLU Volatile Users not clearing down

    Hi all.
    We're having some issues (amongst many) with 11.2.1 DLU policy and it not clearing volatile users accounts down when it should. We currently have the student policy to clear down after 2 days, but this is not happening.
    It's possible our many other Zen issues is having an effect, but we were getting this on Windows 7 workstations prior to 11.2.1 also.
    Setup is 11.2.1 MU2 on servers, currently a mixed MU1 and MU2 agent on devices (it's still slowly rolling out).

    Hi James,
    verify the root cause in your environment:
    are Profiles cleared completely: ProfileList entry under HKLM, ntuser.dat and complete structure under c:\user\... ?
    OR are there remains of folders under c:\users\...
    To my experince under WIndows 7 the problem is mostly only that folders remain from the profile - the rest is removed. The folders are empty in most cases.
    If this is the case and a problem for you, you would need to create a folder deletion script.
    The folder remains have 2 implications:
    USers can see other usernames that logged on to this machine under c:\users\.... However not open or browse it.
    NEw Profiles will be created with username.machine.001 etc. because WIndows Profile Service doesnt find an entry for the user under HKLM ProfileList but the folder c:\users\%username% is occupied so it needs to create it with .001
    this may be only a cosmetical Problem depending on your environment.
    another thing: Im not sure disbling the MS Client makes any sense. Since you experinced delprof2 not working without it - it may lead to problems anyway regarding profile services.
    regards
    Markus
    Originally Posted by JR1CCB
    Hi Markus.
    Many thanks for your reply.
    I have created a bundle using delprof2, and the problem seems to be that it relies on the Client for Microsoft Networks, which we have uninstalled (as tested by running it on a machine with the Microsoft client enabled).
    So the Novell DLU policy is only deleting the users registry hive heys? That seems useless.
    James

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

  • Volatile in java

    Hi,
    I am trying to run the following program to see how volatile variable is shared by 2 threads! The result of the program does not satisfy the definition of volatile. Please help me in checking if it is the right way ... or the codes needs any change.
    package com.msg.jresearch.threads;
    class ExampleThread extends Thread {
         private volatile int testValue;
         public ExampleThread(String str) {
              super(str);
         public void run() {
              for (int i = 0; i < 3; i++) {
                   try {
                        System.out.println(getName() + " : " + i);
                        if (getName().equals("Thread 1 ")) {
                             testValue = 10;
                        if (getName().equals("Thread 2 ")) {
                             System.out.println("Test Value : " + testValue);
                             Thread.sleep(20000);
                   } catch (InterruptedException exception) {
                        exception.printStackTrace();
    public class VolatileExample {
         public static void main(String args[]) {
              new ExampleThread("Thread 1 ").start();
              new ExampleThread("Thread 2 ").start();
    Thanks
    -MS

    MS-Ghotra wrote:
    Hi ,
    Thanks for clarifying it! Appreciate your help.
    I tried following, but unfortunately keeping volatile or no, gives the same result..may be becuase i am updating the instance variable directly.Volatile has nothing to do with it. The real problem in your original code is that you had 2 different objects. Taking away volatile will not fix that, and nobody said or implied that it would.
    If you fix the 2 different objects problem and have both threads working on 1 object, then volatile will matter, and you will definitely want volatile.
    As you said "no multithreading"We said that?
    Trying to create an example of 2 threads working on a common instance. If you can direct me to an example where i can debug & practice it. It will be great.Google for java multithreading tutorial. You'll find lots of examples.
    package com.msg.jresearch.threads;If you want to post code, use code tags so it's readable. Copy paste directly from your original source in your editor (NOT from your earlier post here, which has already lost all formatting), highlight the code, and click the CODE button. Also don't include a bunch of commented out lines. That's just clutter that makes it hard to read. I didn't even try reading your code because of these two issues.

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

  • Use of volatile

    public class MyClass {
         public static void main(String[] a) throws InterruptedException {
              new Thread(new A(),"thread1 ").start();
              Thread.sleep(500);
              new Thread(new A(),"thread2 ").start();
    class A implements Runnable {
         volatile int value = 0;
         public void run() {
              value++;
              System.out.println(Thread.currentThread().getName() + value);
    }Hi, I tried running this code with value being both volatile and not, but I get the same answer each time. Both threads turn value to 1. Shouldn't volatile make it 1 then 2?
    I tried the same thing but making value static, in which case it works as I thought it would have worked with volatile. I'm not too sure what volatile does anymore, could somebody please help clarify all this for me?
    Thanks.

    public class MyClass implements Runnable {
         Other o = new Other();
         public static void main(String[] a) throws InterruptedException {
              MyClass m = new MyClass();
              new Thread(m,"thread1 ").start();
              Thread.sleep(500);
              new Thread(m,"thread2 ").start();
         public void run() {
              o.value++;
              System.out.println(Thread.currentThread().getName() + o.value);
    class Other {
         volatile int value;
    }I looked at this one a bit longer, and I came up with this new example. Is this case more likely to need the volatile keyword as a precaution (as the variable in question is in an indepedent class)?
    Any help on this topic would be really appreciated. I looked up several websites on volatile, but none really clarified the use of volatile (actually, I don't recall whether any mentioned that the caching problem doesn't always happen!).
    Thanks.

  • The "Volatile" Puzzle

    Need a simple example code that works differently with and without "volatile".
    I understand the need for 'volatile' keyword and what it does in java. However, I also vaguely remember reading that this is no longer necessary. i.e., the compiler and jvm of these days takes care of local caching and memory writes very smartly. I tried several examples to see if I can reproduce a case where existence of 'volatile' really makes a difference. But, all my attempts went in vain.
    Here is an example:
    package volatilekw;
    public class Thread1 extends Thread{
    volatile int answer = 0;
    public void setAnswer(int i) {
    answer = i;
    @Override
    public void run() {
    for (int i=0;i<100;i++) {
    System.out.print(answer);
    try {
    sleep(10);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    package volatilekw;
    public class Thread2 extends Thread{
    private Thread1 t = null;
    public Thread2(Thread1 t) {
    this.t = t;
    @Override
    public void run() {
    for (int i=0;i<100;i++) {
    try {
    sleep(10);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    if (i == 1)
    t.setAnswer(1);
    package volatilekw;
    public class Gotgo {
    public static void main(String[] args) {
    Thread1 t1 = new Thread1();
    Thread2 t2 = new Thread2(t1);
    t1.start();
    t2.start();
    Irrespective of whether the "answer" is volatile or not, the output is same with JDK 1.6. I ran several times and even tried decrementing sleep value. If my understanding goes right, the writes of thread2 on answer might not be visible to thread t1 until it caches it. But, this is never the case.
    Is there a good example that demonstrate that 'volatile' does make a difference? I am looking for a piece of code when run with and without 'volatile' gives two different outputs.

    853929 wrote:
    Need a simple example code that works differently with and without "volatile".Impossible to produce reliably. Without volatile, some things can happen, depending on timing, the OS's scheduler, the underlying hardware, other processes running, the JVM implementation, etc., but there's no guarantee that those things ever will happen. However, it's generally bad if they do, so volatile is one way of ensuring that they don't.
    I understand the need for 'volatile' keyword and what it does in java. However, I also vaguely remember reading that this is no longer necessary. i.e., the compiler and jvm of these days takes care of local caching and memory writes very smartly.Nope. The use-case for volatile is still there.
    Volatile was never strictly necessary. We've always been able to accomplish what volatile does by syncing every access to the variable in question. However, when all you need is that all threads see the same copy, and you don't have other atomicity issues to deal with, volatile can save some runtime overhead relative to syncing, and, more importantly, it can make for less cluttered code.
    I tried several examples to see if I can reproduce a case where existence of 'volatile' really makes a difference. But, all my attempts went in vain.Try a multi-cpu box, with not much else happening on it, create as many threads as there are CPUs, and have all threads run a loop from 0 to 10,000 or 100,000,00 or millions that does nothing more than x++ on some shared member variable.
    With volatile, and N threads and a count up to M, you'll see a final value of N x M.
    Without volatile, you might see a value less than N x M.

  • Does JRockit support the volatile keyword?

    Does JRockit support the volatile keyword? If yes, since what version of JRockit is it supported? Will it also be supported on JRockit for Linux.

    A M wrote:
    Does JRockit support the volatile keyword? If yes, since what version of JRockit is it supported? Will it also be supported on JRockit for Linux.AFAIK JRockit always has and always will, including (but not limited to)
    the Linux builds of JRockit.
    However, the actual behaviour of "volatile" hasn't been that well
    defined until Java 5.0, so our interpretation of what volatile should
    mean may or may not have been consistent with SUN's interpretation of
    what volatile should mean.
    Have you been having problems with using volatile? What are you using
    it for in that case? Since volatile might not do what you think it
    does, using locking could be better...
    Regards //Johan

  • Fixing Double-Checked Locking using Volatile

    Oooh - what a scandalous subject title! :)
    Anyhow, I was expanding my knowledge on why the double-checked locking idiom used in Singleton classes fails (after reading that JSR-133 is not going to fix the problem!), when I read http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html and found a spicy section titled "Fixing Double-Checked Locking using Volatile" (at the very bottom of the document).
    As it is quite hard to find information (all sources revisit all the basic problems), I was wondering if anybody could back this up/refute it.
    Just one more thing. I anticipate that many people who are researching this matter would like to have this clarified, so it would be beneficial to keep posts very much on topic. There is already a lot of information available about double locking failures in general.
    The problem this post faces lies in a lot of statements saying "using volatile will NOT fix double-checked locking" that refer (I think) to the current JDK.
    Thanks heaps!

    Volatile only checks that not more than one thread is accessing the variable at the same time (amongst other things of course), so in the example, it could cause problems. Let me explain a little here. Given a situation where two threads wish to aquire the Helper:
    Step 1: Thread 1 enters the method and checks the helper status
    and sees that it is null.
    private volatile Helper helper = null;
    public Helper getHelper() {
      if (helper == null) { // <!-- Thread 1 requires helper, and sees that it is null
         synchronized(this) {
            if (helper == null)
               helper = new Helper();
       return helper;
    }Step 2: Thread 2 enters the method, before the lock can be
    acquired on the this-object and notices that the helper is
    null.
    private volatile Helper helper = null;
    public Helper getHelper() {
      if (helper == null) { // <!-- Thread 2 requires helper also
         synchronized(this) { // and it is still null
            if (helper == null)
               helper = new Helper();
       return helper;
    }Step 3: The first Thread creates a new Helper
    private volatile Helper helper = null;
    public Helper getHelper() {
      if (helper == null) { // <!-- Thread 2 waiting for lock realeas
         synchronized(this) {
            if (helper == null)
               helper = new Helper(); // <!-- Thread 1 creating new Helper
       return helper; //
    }Now for Step 4, there are a few possibilites here. Either Thread 1 returns the helper it created, or Thread 2 can create the new Helper before the Thread 1 returns the Helper. Either way, the result is unwanted.
    private volatile Helper helper = null;
    public Helper getHelper() {
      if (helper == null) {
         synchronized(this) {
            if (helper == null)
               helper = new Helper(); // <!-- Thread 2 creating new Helper
       return helper; // <!-- Thread 1 returning Helper
    }The code can also create interesting situations (deadlocks?) due to the synchronized(this) statement used in a ... creative way in this case.
    I might be wrong of course. Just my �0.02.
    Tuomas Rinta

  • When is volatile needed?

    I know you need to use the volatile keyword when multiple threads might be accessing a primitive or reference without external synchronization. Suppose your class implements Runnable and has one member variable, a final int. The constructor takes an int and simply assigns it to the one member variable. You dump it into an ExecutorService with submit()--do you need to use volatile to make sure that the other threads see the assigned value of the int? The int is only assigned once in the constructor.
    It would seem to me the logical answer here is no; the VM would enforce a memory barrier between unassigned variables turning into assigned variables, but I'm just making sure, since what I've found doesn't really clarify this for me.

    Just out of curiosity, suppose the field was
    non-final. Would volatile still not be needed?If the value never changes, and if you don't let a reference leak out of the constructor, then I'm not sure if you'd need volatile.
    In general, it's possible for one thread to set a value, and another thread to never see it, if there's no syncing and no volatile. I thought that something in the new JMM prevented that in this particular case--i.e., a constructor, but I'm not sure if that's true, or what the details are.
    The answer should be here: http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.4

  • Volatile User's not being removed

    We have a DLU policy that has volatile user implimented. I have been
    noticing that sometimes, the user doesn't get deleted and they have a
    folder in C:\documents and settings\ and their username still exists in
    the windows user management console, which causes problem with the user
    not being able to logon later on. It says "Account created by Novell
    Zenworks" in the description box besides the user name also.
    What causes this and is there anyway we can fix it so that volatile user
    works everytime?
    We are running Netware 6.5 servers and Zenworks 6.5.

    Tried uphclean ?, see TID 10096547
    Cheers Dave
    Dave Parkes [NSCS]
    Occasionally resident at http://support-forums.novell.com/

  • RT target works OK in volatile mode but does not when deployed in non-volatile mode.

    I have developed several applications using the NI cRIO-9073 Integrated chassis. The applications work perfectly well in volatile mode (development), but when I come to deploy the the RT target as an executable the application does not work. Now, I ran the LabVIEW Real-Time 1 Solution application and the same problem occured, in this case, the USER1 LED came on then went off as if an error occured. I finally trapped an error around the shutdown stage, attached, funny thing is though the error code doe not make sense as I am not using the FPGA, running in scan mode, however, I could be missing something.
    (Note: I have obviously modified the Real-Time 1 course solution to use my existing hardware)
    Now this is where it gets puzzling, 3 years ago I did the old RT course, LabVIEW Real-Time Application Development, I have now run the solution for this course, on the same target as the RT1 solution and it works!!!
    I have contacted NI support with no solution to this problem. In the meatime I have a NI cRIO-9704 on order and when it arrives I will try again.
    I really need to know, however what is going on here, does anyone out there have any Ideas? have you experienced any similar problems?
    Thanks
    Neil

    Note to self - Include attachment...
    Error Log
    Status: TRUE
    Code: -65589
    Source: Shared Variable in Chamber Control.vi->RT Main.vi
    This error or warning occurred while reading the following Shared Variable:
    \\NI-cRIO9073-0180F3D1\Thermocouple Mod\Temperature-cRIO
    \\localhost\Thermocouple Mod\Temperature-cRIO
    Error -65589 occurred at an unidentified location
    Possible reason(s):
    CompactRIO:  The FPGA VI you are running does not contain the DMA FIFOs that the RIO Scan Interface requires. Ensure that the modules under the Chassis item in the project match the modules in the chassis, and recompile the FPGA VI.

  • Volatile DLU will not work over wired interface.

    Hi all,
    I've got a weird one that has me stumped. We've got a DLU policy that is working well for our teacher accounts. It is set to user user source credentials, is not volatile, and hasn't caused us issues.
    We're starting to move over and get new Windows 7 machines on the student workstation side. For our students, attempting to get a volatile DLU user set up, with a cache. In testing on desktop machines, it is failing. I'm working now on testing with a laptop and the weirdest thing keeps happening. The DLU policy applies and logins work great with a test student user - but only when attached to the wireless network. Over the wired interface (with wireless completely off), it will not work. The novell client login works, then the dreaded Zen login box comes up, with the name of the volatile login account (that should be local) in the user box. It will not go forward from that point unless I put in a local user name/password. If I do this, I can login thru the zen icon all day long, over the wired interface. This is very similar to the issues we are having on the student workstation machines, or I would just call it odd and move on.
    I've simplified out my network locations to just be one network for now, so that is out as a cause. Completely disabling the wireless adapter, so that it does not show in the zmg-messages log at all did not help either. I can remote control it in that state, and it talks to ZCC.
    The servers are 11.2.2 - Vmware Appliances, have not applied the monthly updates but have them in the queue. Agent the same on the workstation. If anyone has any ideas, I'd love to hear them.
    Thanks
    Pete

    OK - Got this solved. Had applied a registry edit for teacher laptops in the summer based on this TID Support | How to configure "Computer Only Logon If Not Connected" functionality . The login issues only occurred after a teacher account had logged in. The student workstation image had the wired interface listed as 'Public', which caused the novell client to passthru and silently not attempt the login, hence the odd behavior. Oops. Have now limited that regedit to only applying to the teacher laptop workstations. Since these are some of our first student workstations, its not reared its head before. Oh well.
    Pete

  • Can I use MachineID.getBytes() or MachineID.getUniqueID() as a unique identifier?

    The bytes from MachineID.getBytes() are not to be treated as a unique identifier for a device.  It is unique, but is volatile and not suitable to be used as an identifier.  There are various system/hardware events which can cause the MachineID bytes to change over time.  The same rule applies to MachineID.getUniqueID().  If you do .getBytes() and then compare that to AnotherMachineID.getBytes(), even though they can be the same device (but different runtime or browser), you will get a "false" if you're doing a direct byte-by-byte comparison.  This is because during the device individualization process, the device's hardware attributes are interrogated to get a hardware "fingerprint" of the device.  This is stored as a data structure in the MachineID data structure.
    The only resilient way (with limtiations, as stated in the next section) to compare to different devices to determine if they are the same device is to use MachineID.matches().  That comparison is resilient against machine hardware upgrades (changing hard drives, upgrading your video card, upgrading your CPU, reformatting your machine, changing user accounts, using different browsers, etc…). 
    (NOTE): There are 2 known limitations to using MachineID.matches():
    1. MachineID in the Chrome browser (on any platform) a randomly-generated ID string that is not tied to the hardware.  The reason for this is that with the release of Chrome Version 28 browser introduced a sandbox, where code in the browser is not allowed to communicate directly with the hardware layer. This will cause .matches() to fail if comparing a MachineID from Chrome against a MachineID from Firefox, even from the same machine.  This also means that if a user "resets Adobe Access DRM/Licenses", they will lose their ID, and it will be re-generated (as a new ID) the next time DRM content is consumed and their machine has to create a new MachineID.
    2. A similar limitation applies to iOS devices running iOS7 and higher, as a sandbox was also introduced to that platform, preventing applications from directly accessing the hardware.  If you are using iOS7 with a the Primetime Player SDK (PSDK) 1.0 or 1.1, the MachineID for all devices will be the same value, as Apple blocked the device-access APIs (which Adobe Access uses) and caused them to return a static string.  Since all iOS7 devices will return the same string when the device hardware interrogation happens, all iOS7 devices using the the PSDK 1.1 or earlier will return true when MachineID.matches() is called.  Adobe is working on a high-priority fix to this issue, which will be released in a PSDK 1.1 patch/hotfix, where another persistent API is used to bind the MachineID to the device, instead of the blocked device-access APIs.  This new binding mechanism will be persistent across application uninstall/re-installs.
    What is consistent between iOS7 and Chrome 28 (and higher), is that the MachineID will no longer be tied to the hardware attributes of the device.
    cheers,
    /Eric.

    In case you would like to find some way to do something that requires concurrency monitoring (e.g. You run a service and wish to limit the # of devices that can access a your service), the best way to do this would be to move towards a "# of concurrent streams" model, similar to Netflix.
    To do this, you can use Adobe Pass technology called Mai Tai, or implement your own technology (via cookies or authentication tokens) to limit user accounts to no more than XX concurrent streams.
    cheers,
    /Eric.

Maybe you are looking for