[concurrency-interest] How bad can volatile long++ be?
Glen Di Persio
gdipersio at nyc.saic.com
Mon Dec 10 14:09:29 EST 2007
There are plenty of java gurus on this thread who can tell you every
scenario that can happen in theory - I'm not one of those people :) I
will tell you that in practice, you *need* to use an Atomic type or a
synchronized block. Yes, even updating a shared int using ++myInt isn't
Run my attached code to see some missing increments. It may appear ok
for small iterations, but it fails as you add a few threads and crank up
the iterations. Although your question was "can this go really really
haywire", the answer is simply "it definitely goes a little haywire!"
Although the only side-effect I see is lost increments, that alone is
enough - time to make friends with Atomic :)
Example using int, since the problem is bad enough with int:
C:>java -showversion IntRace
java version "1.5.0_11"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_11-b03)
Java HotSpot(TM) Server VM (build 1.5.0_11-b03, mixed mode)
Usage: java IntRace <threads> <reps>
C:\>java IntRace 2 10
Expected result: 20
Actual result: 20
C:\>java IntRace 3 1000
Expected result: 3000
Actual result: 2800
^^^^ 200 lost increments!
From: concurrency-interest-bounces at cs.oswego.edu
[mailto:concurrency-interest-bounces at cs.oswego.edu] On Behalf Of Sam
Sent: Monday, December 10, 2007 10:54 AM
To: Concurrency-interest at cs.oswego.edu
Subject: [concurrency-interest] How bad can volatile long++ be?
I'm fairly certain that ++ is not an atomic operation, even on volatile
variables, on longs (and quite possibly ints). Given that is true
(which it very well might not be), is it suspectible to problems where a
wildly wrong number can be produced (due to different bytes being
updated at different times from different threads), or will it just
cause some increments to effectively not happen?
-------------- next part --------------
A non-text attachment was scrubbed...
Size: 1452 bytes
Url : /pipermail/attachments/20071210/94bb13a2/attachment.obj
More information about the Concurrency-interest