I'm working on my SCJD assignment and I'm thinking about some way to ensure that no one is accessing data file when someone else is shutting down the database. I've found method DvdFileAccess.setDatabaseLocked() in Andrew's code. CleanExit.run() javadoc states "It ensures that the database is in a clean state for shutdown (that is, there are no outstanding writes occuring)", but I'm not sure how this is ensured.
Consider this scenario. Only 2 threads are working. Thread A wants to create new record, persistDvd() method is invoked, Thread A gains the write lock, updates recordNumbers and then releases it (note that it may be still in persistDvd() method). At this point Thread B is shutting down the database, setDatabaseLocked() method is invoked, Thread B gains write lock since Thread A already released it, JVM terminates with Thread A still in persistDvd method (perhaps writing to file).
Welcome to the Ranch and good luck with your assignment.
First off, I didn't read Andrew's SCJD book. But about database shutdown... in my project I have a RMI server shutdown hook that detects if there are any connected clients. At the same time, I set a flag that forbid write operations (update and delete). This shutdown ultimate postpone the actual shutdown for say 2 minutes such that users can perform only read operations once the server is said to shutdown.
Also for Andrew's code, it missed an important "must" requirement for the locking mechanism which I don't know. So I suggest you use Andrew's code as a reference rather than the actual implementation blueprint.
Thanks for your answer. Don't worry I'm not using his code:) Actually my implementation is almost ready, I have only few details left, like this shutdown hook. I was curious how others implemented this and found this solution. Just wanted to share with my doubts;) I know that a lot of people have read this book so that's why I'm asking.
I used a shutdown-hook too. Because my Data class is a singleton with all methods marked synchronized, the shutdown hook will have to own the lock on the single Data class object. So that can happen after a lock or after an update, but not during the execution of the update-method.
As I understand when your shutdown hook is run you just synchronize on Data object ensuring that no other thread can read/write at this moment. But when you shutdown hook ends the lock is released and all threads waiting on your synchronized methods have their chance to run. So there is short period of time between end of your shutdown hook and JVM actual termination which may be used by some thread to start reading/writing. Or maybe I misunderstood something?
To be perfectly safe I'm using ReentrantReadWriteLock to let all threads finish their work and to ensure that no new thread can start reading or writing. At least I hope that this is perfectly safe solution:)