• Post Reply Bookmark Topic Watch Topic
  • New Topic

Synchronization Question

 
Dilip kumar
Ranch Hand
Posts: 360
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a vector to hold locked records. Multiple clients can access this vector. I need to write lock() and unlock() methods. Instead of synchronizing whole methods I�m planning to use synchronized blocks. I�m wonedring if my logic is okay. I�m not that good in threads.
Lock(int recordnumber) {
while(true) {
   If record not exists in vector
       add recordnumber to vector
   else
       synchronized(this) {
           wait();
       }
}
}
UnLock(int recordnumber) {
while(true) {
   Remove record from vector
   synchronized(this) {
       notifyAll();
   }
}
}
Thanks
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, your logic isn't right. When you are outside a synchronized block, anything may happen between [/i]any[/i] two statements. Consider the following fragment from your code:

What happens if, between your test ("record not exists") and the setting of the lock ("add record"), another thread locks the same record? You will be handing out two locks on the same record. So you will have to pull this into the synchronized block.
In fact, I would encourage you to ditch the Vector in favour of an unsynchronized collection class (ArrayList, probably). The fact that the Vector is synchronized will only encourage you to use wrong logic, and unnecessarily slow down your application.
- Peter
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!