Re: Synchronize on a integer value
Tuesday, April 8, 2003 10:26 AM
You've presented a hard problem. I assume you have disjoined parts of your code which need to mutual agreement on the lock for a given "logical" record (your "id"). The easiest approach may be redesign (with singletons for your IDs).
Without a redesign, I think your two suggestions are the only way to go. You may also want to consider the characteristics of your app (which I am not familiar with). Are the odds that the different modules want the same "id" high or low? You can get past some of the Object accumulation issues by changing your semantics from "synchronized" to "get/release lock" on a common class which keeps Objects for each ID in an internal collection. When the lock count goes to zero, you can dispose of the ID in your collection. Of course, you have to be careful of exceptions which would cause you to loose track of your locks (and cause deadlocks).
Either way, I agree with the suggestion to check out Doug Lea's book. He lays this stuff out nicely.