Win a copy of Five Lines of Code this week in the OO, Patterns, UML and Refactoring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Question about synchronized collection classes

Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

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
    Bookmark Topic Watch Topic
  • New Topic