Forums Register Login

Question about synchronized collection classes

+Pie Number of slices to send: Send
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
CLUCK LIKE A CHICKEN! Now look at this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 740 times.
Similar Threads
My Locking...Advice needed...
Database Thread Safety, pls review
NX: Locking and threads
Lock question!
Passed 337/400
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 23:05:33.