Reputation: 921
The following is the code snippet from java concurrency in practice book while discussing open calls. The point I'm not getting is that the way setLocation method is declared, it is already synchronized and again calling the synchronized(this) block within the same method, why this ? Is it type mistake ? The synchronized method already holds the lock on this method then why again for the same object ?
@ThreadSafe
class Taxi {
@GuardedBy("this") private Point location, destination;
private final Dispatcher dispatcher;
...
public synchronized Point getLocation() {
return location;
}
public synchronized void setLocation(Point location) {
boolean reachedDestination;
synchronized (this) {
this.location = location;
reachedDestination = location.equals(destination);
}
if (reachedDestination)
dispatcher.notifyAvailable(this);
}
}
Upvotes: 0
Views: 76
Reputation: 691685
It's an error in the book. See the errata
In Listing 10.6, Taxi.setLocation should not be a synchronized method. (The synchronized block in its body is correct, however.)
Upvotes: 5