I want to write code to update an XML file. I need to use synchronization to prevent multiple simultaneoue updates or lookups while data is being changed. Is there an accepted pattern for writing code to do this? It seems like a simple idea until you start to actually write the code. Paul
Michael Morris
Ranch Hand
Joined: Jan 30, 2002
Posts: 3451
posted
0
Hi Paul, Well anytime you synchronize a method or object your goal is prevent two or more threads from modifying some certain data. The most straight forward way to do that is to synchronize whatever object that encapsulates that data. If your XML file is encapsulated as a Document inside any method that modified the Document you could call wait() on the Document object whenever another thread was already modifying. Of course once the modifying thread finishes, it must call notifyAll() on the Document object so any waiting threads can have their chance to play. I personally prefer to synchronize methods as opposed to objects since the latter is more prone to deadlocks even though it may take a few more microseconds to do so. I'm not familiar with any patterns associated with protecting data from concurrent modification but there may be. For the most part it's not as complicated as it seems so long as the data you're trying to protect is encapsulated in a single object. Hope this helps, Michael Morris
Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher