File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Threads and Synchronization and the fly likes Atomic Operations Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Atomic Operations
 
Similar Threads
Synchronization
Changing directory structure on the server
Private modifier problem
int is atomic!!!
Can someone tell me why?