This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I am using the facade pattern following Andrew Monkhouse's book and am planning to use RMI for the network connection (project is UrlyBird). So, I will have several Data (the facade object) classes, but only one delegatee for the database operations, like this:
This delegatee itself uses some static helper objects, which get their initial (and, for databaseDescriptor, also final) state during the delegatee's initialization:
For example, the databaseDescriptor parses and keeps the header information, and the positionProvider gets a list of deleted positions at startup.
As these helper classes have state, I think that the code as-is is not thread-safe regarding creation of the fileDatabase delegatee. I am wondering how to make it thread-safe:
1) Evidently I cannot make this field immutable according to the definition "is transitively reachable from a final field, has not changed since the final field was set, and a reference to the object containing the final field did not escape the constructor" (http://jeremymanson.blogspot.com/2008_04_01_archive.html), as I cannot make it final and during all the actions that happen during the initialization of fileDatabase there will surely escape some reference...
2) Making the field "private static Database database" volatile, would this be sufficient, as all threads should get the same results anyway? Or could still corruption result during the following actions? (Make all static fields volatile?)
3) Monitor the initialization process like in Effective Java 2, item 74, with a State enum and setting the state to initialized after all actions are finished only?
4) Very ugly I suppose: make the Data constructor itself synchronized?
5) Double-checked locking in the constructor?
BTW I'm not sure about the example project in the Monkhouse book - it does not do any synchronization at that point either, but the dVDFileAccess class seems to have state too (the recordNumbers map)?
I'd be very thankful for your help & responses with this, Sigrid
many thanks for your reply. In fact, as I read in Effective Java 2 (Item 71), the double-checked locking works now, due to a change in the Java Memory Model. But the field has to be volatile for that (I forgot to mention this in my post). I would be very curious to know how other people handled this problem? In fact I am still not even sure I have to synchronize here, as AFAIS there is no equivalent synchronization in the DVDDatabase sample project - perhaps I'm overly cautious? (Mr Monkhouse perhaps if you read this... could you give me a hint ?)