Wondering if this approach is safe and workable with Threads and hibernate?
One thread is responsible for writing data to the database every few seconds to a minute. I have other threads that start about every five minutes to read the database for the last record entered and do with the data what they will -- they do not update the record in the database at all.
I had thought about sharing the object with all the threads but the above would separate out writes and reads. The query should be easy to just grab the last record as most databases allow for that -- not sure about hibernate (still getting into it.) The only issue I see might be if need to create a thread that would read the database every three seconds and in that case it might be better to share the object.
What you want is a read-many-write-one lock: reading threads can have access unless another thread is writing; other reading threads are not a problem. Writing threads must wait until all other reading and writing threads have finished. don't know if this has been implemented in Java yet but it's not that hard to implement yourself if it isn't.
Rob Prime wrote:What you want is a read-many-write-one lock: reading threads can have access unless another thread is writing; other reading threads are not a problem. Writing threads must wait until all other reading and writing threads have finished. don't know if this has been implemented in Java yet but it's not that hard to implement yourself if it isn't.
Further to Rob comments( thanks Rob). There is in java 5 ( concurrency util) something called ReadWriteLock.
If we look at the JAVA DOC; it says:
"A ReadWriteLock maintains a pair of associated Lock locks, one for read-only operations and one for writing. The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive.
All ReadWriteLock implementations must guarantee that the memory synchronization effects of writeLock operations (as specified in the Lock interface) also hold with respect to the associated readLock. That is, a thread successfully acquiring the read lock will see all updates made upon previous release of the write lock. "
Now the last statement is very interesting which means there will be no stale data so any read thread will capture the latest write thread so this is a guranttee of visibility across all reader threads.
Now if we compare the performance of ReadWriteLock implementation ( ReentrantReadWriteLock) w.r.t. ReentrantLock; we can see on the average for more then 4 threads we will get almost double throughput ( measure of taks compleleted per unit of time)
Now if we give an example here to clarify the concept more; please notice, I am assuming you are using java 5 and above.