All,
I am writing a multithread program. The class which extends Thread has a static Hashtalbe<Integer, SessionData> sessionDataTable.
In the class, I will do something to change the sessionDataTable, like insert a new SessionData object into it, delete a SessionData object from it or modified the SessionData objects in the Hashtable.
At the end, I will write the Hashtable to a file using ObjectOutputStream, the method is something like
public static synchronized void saveDataSessionState()
{
...
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(Constants.logFile));
oos.writeObject(sessionDataTable);
...
}
I am wondering what will happen if one thread is doing oos.writeObject(sessionDataTable); but other threads are modifying the sessionDataTable (like what I said above) at the same time somewhere outside this method. Will the above method cause exception when writing the object to file?
If yes, how could I avoid the problem? Use lock? But then I need to put a lock whenever I modify the Hashtable.
Thanks.
Based on my examination of the code, I think that you won’t have any problems. The accessors and mutators for the
Hashtableclass are declared assynchronized, and so is the privatewriteObjectmethod onHashtablethat does the serialization. That should be sufficient to ensure that nothing can change theHashtablewhile the serializer is looking at it.However, you could get into trouble if something changed the state of a
Hashtablekey or value while serialization was occurring. (I don’t know if default serialization of an object is performed holding an object’s mutex. I suspect not because of the cost of locking unnecessarily, the fact that a simple mutex won’t necessarily achieve the required exclusive access, and the potential risk of deadlocks.)