• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about synchronized collection classes

 
Ciaran Cahill
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
Just a quick question about the use of synchronized collection classes (like ArrayList or a Map wrapped in a synchronized Collections wrapper).

At the moment I am thinking about implementing the locking mechanism in the database code for the B&S project by using a synchronized block that gets the lock of an individual Contractor object - as follows:
(each Contractor object represents an entry in the database)


public long lock(int recNo) {

// Get the Contractor object from the ArrayList of Contractors (this list
// will be synchronized):
Contractor contractorToLock = contractorsList.get(recNo);

// Get the lock of this Contractor object:
synchronized (contractorToLock) {

// Main locking code here:

// Get the current thread
Thread thisThread = Thread.currentThread();

// Put this thread into a SortedMap called 'waiters', which maps
// Contractor objects (the keys) to accessing threads (the values).

waiters.put(contractorToLock, thisThread);

Finally use the SortedMap to check here to see if it is ok to write or modify the Contractor object. If the check does not succeed - wait().
The unlock() method will call notifyAll() to wake up the thread.

...

}

}
}

This is very simplified but the idea of using the 'waiters' SortedMap is to see which threads are accessing the Contractor object. Because it will keep the order of its elements, we can wait() until all 'writes' have gone through for example before we read.

The overall goal is to allow threads to lock on individual records, by checking the state of play in the SortedMap, rather than getting the lock to the entire contractorsList ArrayList for example.

So...
Is this threadsafe - given that the ArrayList and the SortedMap are synchronized?
Also - is it a good idea to lock on individual records at all? Would it be better to synchronize on :
1. the waiters HashMap,
then 2. the contractorsList ArrayList, then 3. the Contractor object itself when locking?
Even though this could be a bottleneck?

Hope this is clear
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic