Tuesday, November 20, 2012

volatile and transient

Access modifiers to fields of classes: volatile and transient

In Java every variable marked with a transient modifier will not be serialized (because it will be excluded by Java object serialization subsystem when serializing an instance of the class). You can use the transient keyword to indicate to the JVM that the transient field is not part of the persistent state of an object.

The volatile modifier tells the Java Virtual Machine that every recording to this field should always be synchronously flushed to memory, and that every reading of this field should always read from memory. That is why fields marked as volatile can be safely accessed and updated in a multi-thread application without using native or standard library-based synchronization (except long or double fields, which may be non-atomic on some Java Virtual Machines. However, it always can apply to reference-typed fields) .

See more in java.util.concurrent.atomic packacge e.g.:
AtomicIntegerFieldUpdater     A reflection-based utility that enables atomic updates to designated volatile int fields of designated classes.
AtomicLongFieldUpdater     A reflection-based utility that enables atomic updates to designated volatile long fields of designated classes.



 

No comments: