Writing an object to a file when other threads are modifying the object
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 synchro开发者_StackOverflow社区nized 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 Hashtable
class are declared as synchronized
, and so is the private writeObject
method on Hashtable
that does the serialization. That should be sufficient to ensure that nothing can change the Hashtable
while the serializer is looking at it.
However, you could get into trouble if something changed the state of a Hashtable
key 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.)
ConcurrentHashMap is what you need. This, however, will solve only the hash map concurrent access issue.
At the same time the SessionData would need to be made immutable, which would ensure that a particular instance would never change once created. If a hash map entry needs to be modified -- simply replace it with a new instance of SessionData.
精彩评论