The moose likes Developer Certification (SCJD/OCMJD) and the fly likes Thread safety in the database access. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Developer Certification (SCJD/OCMJD)
Bookmark "Thread safety in the database access." Watch "Thread safety in the database access." New topic

Thread safety in the database access.

Elena Taube

Joined: Dec 06, 2005
Posts: 21
Hi all,
I have defined the Database class that works with the RAF instance. It is a singleton and contains one instance of RAF. Every Data class works with this Database class.
I am confused about the correct implementation of the thread safety, in other words synchronization in this class.
I know that there are two ways of the synchronisation for my case:

1. synchronize every method that works with the RAF.
2. synchronize in every method the RAF instance.

But I don�t see the difference and what is correct implementation for my case. The only difference is that for the first case only one client has Database class access in a time.
For the second one the only one client has RAF access in a time. But I couldn�t understand what the correct implementation is.

Could you help me?
Thanks a lot for your Help!!!
[ December 27, 2005: Message edited by: Elena Taube ]
Alex Sharkoff
Ranch Hand

Joined: Apr 11, 2004
Posts: 209
Hi Elena,

well, I guess both of these approaches are correct. However, I'd go with the second one, ie synchronising on raf instance, because it gives you a better control and performance ( eg, before accessing raf in a multi-thread safe way you might want to do something in the Database methods that does not require synchronisation ).

Hope it helps.

Alex (SCJP 1.4, SCBCD 1.3, SCWCD 1.4, SCJD 1.4)
HaoZhe Xu
Ranch Hand

Joined: Nov 03, 2003
Posts: 222
Depends on your assignment, I guess the Thread safety particularly means locking of record, e.g. when a record is being modified by one thread, it cannot be accessed by other threads.

you can do this: have a HashMap, when a thread is modifying a record (like booking the record for some assignments when you need to modify the booked field or owner field), firstly check the HashMap, see if the id of the record(usually record number) is one of its values, if so, yield; otherwise, put the thread itself and the record id as key and value respectively to the hashmap, then modify the record, after modifying, get the key-value pair out from the hashmap -- hope my idea is right, but it's simple anyway, you can have a LockManager that specifically do these.

best regards

I agree. Here's the link:
subject: Thread safety in the database access.
jQuery in Action, 3rd edition