Tip #-2 Never lock on a Class

I just learned a lesson today the usual way.  I.e. the hard way!  

Conclusion -- never do this:

synchronized(getClass()) { ..... }

Why?

The intent is obviously to serialize the block against ALL instances.  About the only requirement is that the object be unique and global.

Oops!  The object is not unique!  What if the method is called from a derived class?  Then the lock object is totally different.  That is what happened to me.

This is a much better way to do such things:

class Foo {

private final static Object myLock = new Object();

public void someMethod() {

    synchronized(myLock) { ....... }

myLock is global, unique and is self-documenting.

Comments:

Good point! Know what you are locking on.

Posted by Kedar Mhaswade on July 09, 2008 at 09:28 AM PDT #

Post a Comment:
  • HTML Syntax: NOT allowed
About

ByronNevins

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today