This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I need to refactor some code because I have no idea how this is supposed to work in a multi-threaded environment. So here is what's going on:
- The UI is reading XMLs from a URLs. In order to avoid repetition of same code everywhere, methods like connect method (to open URLConnection and read xml string) and getDocument (to create a Document object from URL) were made static and are being used as Util.getConnection() or Util.getDocument() all over the code.
This is working fine until now, but I am not confident if this will still work when there are more than 1 person accessing the UI?
We'd have to see the code to know for sure. When you call Util.getConnection(), does it just return the opened connection object to the caller (thread safe) or does it store it internally (not thread safe)? How are connections closed when you're finished with them? I assume that Util.getDocument() must have a connection to work with. Where is that coming from?
Threads are a difficult topic. Try to walk through imaginary scenarios where one thread gets part way through its work, but then has to wait while the second thread runs. Can something the first thread needs be modified by the second thread?
This topic is too complicated for beginners, and it is mainly about multi-threading issues, so I'll move it over to the Threads and Synchronization forum.
Yes, those look okay by themselves. If everything that is created is held as local variables, you are fine because each Thread gets its own copy of local variables. The only question comes out of shared data (data that is stored as static or instance variables, or which are passed in as parameters or returned as results).
From the code you provided, the only piece of the puzzle you would need to worry about is the Document. The Document is mutable, so if multiple threads had a hold on the same Document they could cause problems by simultaneously changing it, so you would need to make sure that the Document doesn't leak to multiple threads. That isn't something you can do in this Util class though.
Joined: Nov 10, 2008
Thank you Steve, your reply is helpful. So how do I make sure that the Document does not leak to multiple threads? I hope this can be done in the object that calls this method.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com