[concurrency-interest] Volatile / Sychronized?

Richie.Jefts at APCC.com Richie.Jefts at APCC.com
Wed Dec 20 16:41:27 EST 2006


It depends on whether the fields in question are exclusive to each other. 
But if one variable is not dependent on another, volatile should be 
sufficient.

class Foo {
        private volatile int x;
        private volatile int y;

        public int getX() {
                return x;
        }

        public int getY() {
                return y;
        }

        public synchronized void set(int x, int y) {
                this.x = x;
                this.y = y;
        }
}

In this example, the setting of (x,y) is an atomic operation, but the 
reading of these values is not. A thread calling getX() could read a new 
value of x before the "this.y = y" occurs and therefore break the contract 
of class Foo.

richie




"Kessel, Chris" <ckessel at c-cor.com> 
Sent by: concurrency-interest-bounces at cs.oswego.edu
12/20/2006 03:31 PM

To
"Brian Goetz" <brian at quiotix.com>, "First Last" <chancer357 at hotmail.com>
cc
concurrency-interest at cs.oswego.edu
Subject
Re: [concurrency-interest] Volatile / Sychronized?






I have various POJO's that I've just used volatile on and skipped
synchronization, except in the few instances where 2+ fields are always
changed at the same time.

Wouldn't volatile be sufficient in that case? My only real concern is
avoiding stale reads.

-----Original Message-----
From: concurrency-interest-bounces at cs.oswego.edu
[mailto:concurrency-interest-bounces at cs.oswego.edu] On Behalf Of Brian
Goetz
Sent: Wednesday, December 20, 2006 1:21 PM
To: First Last
Cc: concurrency-interest at cs.oswego.edu
Subject: Re: [concurrency-interest] Volatile / Sychronized?

> Please clear up something about the proper use of volatile for me. I'm

> having difficulty understanding when volatile is sufficent. 

I'd add to this discussion that if in doubt, steer away from volatile. 
Except for very simple cases (such as "public volatile boolean 
shutdownRequested"), it is tricky to get right.
_______________________________________________
Concurrency-interest mailing list
Concurrency-interest at altair.cs.oswego.edu
http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest


_______________________________________________
Concurrency-interest mailing list
Concurrency-interest at altair.cs.oswego.edu
http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest

-------------- next part --------------
An HTML attachment was scrubbed...
URL: /pipermail/attachments/20061220/50f014d2/attachment-0001.html 


More information about the Concurrency-interest mailing list