Link to home
Start Free TrialLog in
Avatar of DJ_AM_Juicebox
DJ_AM_Juicebox

asked on

volatile keyword in java 1.3

Hi,

Does the volatile keyword make a primitive safe to read/write from multiple threads without guarding it? I don't know where I read that but - something like:

public class Test
{
    public volatile m_flag;

    new Thread() {
        public void run() {
            while(...) {
                m_flag = false;
                print(m_flag);
            }
        }
    }.start();

    new Thread() {
        public void run() {
            while(...) {
                m_flag = true;
                print(m_flag);
            }
        }
    }.start();
}

I mean is setting and getting m_flag atomic now, so no thread is reading or writing it at the same time? I can put a guard object around it but it seems annoying to do for a simple boolean primitive,

Thanks
Avatar of mnrz
mnrz

no I think  this is not safe, you had better to change it into this line:

private volatile java.util.concurrent.atomic.AtomicBoolean m_flag = false;

atomic types make your variable safe in read/write concurrently

private volatile java.util.concurrent.atomic.AtomicBoolean m_flag = false;

Open in new window

mnrz: java.util.concurrent is not available to 1.3 as far as I know. Has this changed?
ASKER CERTIFIED SOLUTION
Avatar of mbodewes
mbodewes
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
yes in version 1.3 you need to synchronize it
Avatar of DJ_AM_Juicebox

ASKER

ok thanks