I have a class that updates a counter in a static class that holds a bunch of counter variables.
Multiple Message Driven Beans have the potential to update this particular counter using the pre-increment operator:
A coworker has pointed to a reference in a book where if you do this:
y = ++x;
the assignment can be preempted by another thread incrementing x before the assignment to y is complete.
Is this the case for ++x operation? Or is this considered an atomic work unit by the JVM and therefor not 'pre-emptable'?
Originally posted by Rob Ross:
Here's another quirky issue:
long x = 256;
long y = -1048;
x = y; //not atomic, so not thread safe!
reads and writes of 64 bit quantities are NOT required to be atomic in the spec. You have to either synchronize, or you can use the volitile keyword to force atomicity.
Again, whats the objective? the only way to ensure a proper value is synchronize, volatile will not give you the necessary multithreaded protection. volatile will prevent rediculous numbers that never occured in your program, but it won't let you safely read or write the variable.
In general, even if volatile is implemented correctly its usefulness is limited at best, and it's very easy for people to make subtle mistakes with it which make their programs unreliable. So it should be avoided unless the user is very sure of what they're doing. And given the current implementation problems, it should really be completely banned from programs. But who knows, they might fix it someday, so that it's only useless 95% of the time... :roll:
Originally posted by Jim Yingst:
Well, there are cases where volatile could actually be useful if it were implemented correctly. For example if most threads are interested only in only atomic operations like reading a variable, volatile can be a faster way for them to access the variable, and still safe.
Watch your tone mister! volatile is not broked, JVMs are broken
In your example I can not understand why you would use any synchronization at all. You obviously dont care to get an exact value from the variable, and if you can write without the write breaking(because of volatile ) then you don't even need to synchronize.
In your example I can not understand why you would use any synchronization at all.
Yeah, in this particular example I guess the setters wouldn't need any synchronization, if the JVM were to implement volatile correctly. :roll: I had originally been thinking of a slightly different example, but altered it before I submitted the post, and neglected to bring all my comments into sync with the new example.