Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 587
  • Last Modified:

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
0
DJ_AM_Juicebox
Asked:
DJ_AM_Juicebox
  • 3
  • 2
1 Solution
 
mnrzCommented:
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
0
 
mnrzCommented:

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

Open in new window

0
 
mbodewesCommented:
mnrz: java.util.concurrent is not available to 1.3 as far as I know. Has this changed?
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
mbodewesCommented:
No, this does not work, the change may happen in between the setting and the printing. So the print statement may print about anything. There is nothing locking the volatile variable between these two states. You might want to synchronize the code parts setting and printing the variable instead.
0
 
mnrzCommented:
yes in version 1.3 you need to synchronize it
0
 
DJ_AM_JuiceboxAuthor Commented:
ok thanks
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now