I have a chunk of code that I'm synchronizing, however it throws a NPE once in a while.
I could easily avoid the NPE by making a verification that list is not null before the "synchronized" guarded area, however I read that some people recommend to use Semaphores instead synchronized; How could I use a Semaphore in my code?
I don't think that Semaphore, or other Locking mechanisms necessarily work to fix your problem.
If I understand your intent:
1) You have multiple Lists, each associated with a Session.
2) Some threads will be waiting on their Session's List
3) This code will wake up all threads which are waiting on one Session's List
The problem is that the Session you are working on has no List associated with it. You could substitute a Lock, or a Semaphore for synchronizing on the List, but that Semaphore or Lock would have to be Session specific, and so would need to be stored in a map pretty much the same way as the List is, and so you would still have to check if the Semaphore or Lock existed before using it.
You should add a null check. If the List returned from the Map is null, don't try to use it (you don't need to anyway - nobody could be waiting on it if it isn't in the Map correct?).
posted 11 years ago
yes, you are right. I just wanted to make it more elegant if possible.