Atomic Access and Assignment
Variables shared between multiple
threads (e.g., instance variables of objects) have atomic assignment
guaranteed by the Java language specification for all data types
except for long
s and double
s.
Actually, the storing of a value into a variable takes two primitive
operations, a
store
and a write. However, the language specification
also states that once a store operation occurs on a particular
variable, no other store operation is allowed on that variable until
the write operation has occurred. The specification allows
long
s and double
s to be stored
in two separate sets of store+write operations, hence their exception
to atomicity. A similar atomic specification applies for reading
variables.
This
means that access and update of variables are automatically
synchronized (as long as they are not long
s or
double
s). If a method consists solely of a
variable access or assignment, there is no need to make it
synchronized
for thread safety, and every reason not to do so for performance.
Thread safety extends further to any set of statements that are
accessing or assigning to a variable independently of any other
variable values. The exclusion here precludes setting a variable that
depends on the value of another variable as being thread-safe; this
would be two separate operations, which is inherently not
thread-safe. For example:
public void setMe(Object o) {me = o;} public Object getMe( ) {return me;}
are thread-safe methods, with no need for
synchronized ...
Get Java Performance Tuning now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.