The moose likes Threads and Synchronization and the fly likes Atomic Operations Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Atomic Operations" Watch "Atomic Operations" New topic
Author

Atomic Operations

amit sanghai
Ranch Hand

Joined: Dec 05, 2000
Posts: 231
1) Why do atomic operations not need to be synchronized?
One example is mentioned in "Thinking in Java" Book (http://www.smart2help.com/e-books/tij-3rd-edition/TIJ315.htm), where, an atomic operation needs to be synchronized, otherwise it fails.
code:
public
class SynchronizedEvenGenerator implements Invariant {
private int i;
public synchronized void next() { i++; i++; }
public synchronized int getValue() { return i; }
// Not synchronized so it can run at
// any time and thus be a genuine test:
public InvariantState invariant() {
int val = getValue();
if(val % 2 == 0)
return new InvariantOK();
else
return new InvariantFailure(new Integer(val));
}
public static void main(String[] args) {
SynchronizedEvenGenerator gen =
new SynchronizedEvenGenerator();
new InvariantWatcher(gen, 4000); // 4-second timeout
while(true)
gen.next();
}
} ///:~
It is mentioned:
"If you were to blindly apply the idea of atomicity to SynchronizedEvenGenerator.java, you would notice that
public synchronized int getValue( ) { return i; }
fits the description. But try removing synchronized and the test will fail, because even though return i is indeed an atomic operation, removing synchronized allows the value to be read while the object is in an unstable intermediate state."
2) It is also mentioned :
"The atomic operations commonly include simple assignment and returning a value when the variable in question is a primitive type that is not a long or a double."
Why not long and double?
John Smith
Ranch Hand

Joined: Oct 08, 2001
Posts: 2937
"The atomic operations commonly include simple assignment and returning a value when the variable in question is a primitive type that is not a long or a double." Why not long and double?
long and double are the only primitive types that are 64-bit long. My guess is that reading and writing a 64-bit value requires more than one operation and therefore is not considered atomic.
Eugene.
 
 
subject: Atomic Operations
 
Threads others viewed
Synchronization
Private modifier problem
int is atomic!!!
Can someone tell me why?
Changing directory structure on the server
MyEclipse, The Clear Choice

cast iron skillet 49er

more from paul wheaton's glorious empire of web junk: cast iron skillet diatomaceous earth rocket mass heater sepp holzer raised garden beds raising chickens lawn care CFL flea control missoula heat permaculture