JS Ext

Monday, December 16, 2013

Thread Saftey: Protect your Lock

Java provides the ability to lock on yourself.  You can do this using the synchronized keyword as part of a method definition.  Many programmers don't use that form of the keyword, though.  You may have seen this code before:

public class MyObject {
 private final Object lock = new Object();
  public void someMethod() {
   synchronize ( lock ) {
   // actually do something
  }
 }
}

There are two points to having a private lock like this.  For both scenarios, imagine if you synchronized on the method instead of the lock.

1) If a developer extends MyObject, then any methods that they write that synchronize on the method will block your methods as well.  Both codes are critical sections of the same lock.  This could either be a good thing or a bad thing.  If the developer extending MyObject doesn't look at (or doesn't have access to) the source code, then it could be a really bad thing.  Deadlocks of occured doing this.  You can also run into performance issues.  If your class is senative to those types of issues, then I highly recommend making the object final, regardless of the synchronization type you use.  This prevents people from extending your class

2) A developer that is using MyObject can synchronize on an instance of the object.  If the implementation of MyObject is


In my opinion, it is better to be educated so that you can make the right decision for your scenario.  The problem with a 'private' lock is you no longer let users of your api know that a method is synchronized.  JavaDoc and various auto-complete technologies let the user know that a method is synchronized.  They use the method keyword to determine that.  Over use of the private lock pattern leads to a bunch of synchronized methods that are documented as not synchronized.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.