Java Reference
In-Depth Information
only when it is absolutely neededfor example, a method that performs a
complex calculation and then assigns the result to a field often needs to
protect only the actual field assignment not the calculation process.
Second, synchronized statements allow you to synchronize on objects
other than this , allowing a number of different synchronization designs
to be implemented. Sometimes you want to increase the concurrency
level of a class by using a finer granularity of locking. It may be that
different groups of methods within a class act on different data within
that class, and so while mutual exclusion is needed within a group, it
is not needed between groups. Instead of making all the methods syn-
chronized, you can define separate objects to be used as locks for each
such group and have the methods use synchronized statements with the
appropriate lock object. For example:
class SeparateGroups {
private double aVal = 0.0;
private double bVal = 1.1;
protected final Object lockA = new Object();
protected final Object lockB = new Object();
public double getA() {
synchronized (lockA) {
return aVal;
}
}
public void setA(double val) {
synchronized (lockA) {
aVal = val;
}
}
public double getB() {
synchronized (lockB) {
return bVal;
}
}
public void setB(double val) {
synchronized (lockB) {
bVal = val;
 
Search WWH ::




Custom Search