Java Reference
In-Depth Information
field must be
synchronized
. This is yet another reason to prefer accessor
methods to
public
or
protected
fields: Using methods, you can synchron-
ize access to the data, but you have no way to do so if the fields can be
accessed directly outside your class.
With the
synchronized
declaration, two or more running threads are guar-
anteed not to interfere with each other. Each of the methods will ex-
ecute in mutual exclusiononce one invocation of a method starts exe-
cution, no other invocations of any of the methods can commence until
the original has completed. However, there is no guarantee as to the or-
der of operations. If the balance is queried about the same time that a
deposit occurs, one of them will complete first but you can't tell which.
If you want actions to happen in a guaranteed order, threads must co-
ordinate their activities in some application-specific way.
You can ask whether the current thread holds the lock on a given object
by passing that object to the
Thread
class's static
holdsLock
method,
which returns
true
if the current thread does hold the lock on that ob-
ject. This is typically used to assert that a lock is held when needed. For
example, a private method that expects to be invoked only from
syn-
chronized
public methods might assert that fact:
assert Thread.holdsLock(this);
You will also occasionally find it important that a certain lock not be held
in a method. And in some rare circumstances you might want to choose
whether or not to acquire a given lock depending on whether or not an-
other lock is held.
When an extended class overrides a
synchronized
method, the new
method can be
synchronized
or not. The superclass's method will still
be
synchronized
when it is invoked. If the unsynchronized method uses
super
to invoke the superclass's method, the object's lock will be ac-
quired at that time and will be released when the superclass's method
returns. Synchronization requirements are a part of the implementation
of a class. An extended class may be able to modify a data structure
such that concurrent invocations of a method do not interfere and so the