|
Fine-Grained Locking
Listing 2. The explicit block is better than the standard implementation (synchronizing all methods) because both methods can run concurrently, which reduces locking costs and increases scalability. The caveat is that you can't have two threads invoking the same method on the same object, which is the consistency we want to enforce. import java.util.Date;
/**
* Illustrates fine-grained locking.
*/
public class Person1
{
private String name, surname;
private Date birth, death;
private final Object nameLock =
new Object(), dateLock = new Object();
/**
* This setter can run asynchronously
* with setDates().
*/
public void setNames(
String name, String surname)
{
synchronized (nameLock)
{
this.name = name;
this.surname = surname;
}
}
/**
* This setter can run asynchronously
* with setNames().
*/
public void setDates(Date birth, Date death)
{
synchronized (dateLock)
{
this.birth = birth;
this.death = death;
}
}
}
|