Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

NPE in synchronized  RSS feed

 
Robert Garrido
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

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?

Thanks a lot.
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?).
 
Robert Garrido
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes, you are right. I just wanted to make it more elegant if possible.

Thanks!
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!