Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 17th, 2012  |  syntax: None  |  size: 0.64 KB  |  hits: 10  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Java synchronized - am I doing it right?
  2. public void setNewSessionListener(NewSessionListener newSessionListener) {
  3.     if (this.newSessionListener != null)
  4.         synchronized (this.newSessionListener) {
  5.             this.newSessionListener = newSessionListener;
  6.         }
  7.     else
  8.         this.newSessionListener = newSessionListener;
  9. }
  10.        
  11. private static final Object LOCK = new Object();
  12.        
  13. synchronized (LOCK) {
  14.     if (this.newSessionListener == null) this.newSessionListener = newSessionListener;
  15. }
  16.        
  17. private ReentrantLock lock = new ReentrantLock();
  18.  
  19. lock.lock();
  20. try {
  21.   // do your synchronized code here.
  22. }
  23. finally {
  24.   lock.unlock();
  25. }