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 am working on an application which EngineFactory class file is written based on Singleton pattern and it is not thread safe. So when I run only one thread at a time the application is working fine. But when I tried running two threads in parallel at the same time the application is not working correctly. I am new in multithreaded environment. I workaround with “synchronized” to fix this issue but not success. I would really appreciate if someone can give me any idea how I can fix this issue.
The Initial code was like below:
Then I tried with “synchronized”, but no success. Here is the code:
Second is a question about exactly what you're trying to do.
From my reading of the code, all you're synchronizing is the creation of the singleton object but I would think that synchronizing the methods of the instance is even more important.
So my first question is why make the EngineFactory a signleton? Does not being thread safe mean multiple threads should not call a single instance or does it mean multiple instances should not be created? If it's the former each thread could have it's own instance. If it's the latter then I would suggest either modifying the source or creating a wrapper to synchronize the method calls.
Synchronizing methods is not a simple, you can do it blindly without understanding how it's used, kind of thing. In other words it's often the case that the lack thread safety is due to multiple step transactions keeping state in the object.
Consider this oversimplified example of getting data from a website
I know it's a silly example but the point I'm trying to make is that if you make DataGetter a singleton object then the three steps have to be done as an atomic operation, no other thread can access it until all three steps complete. On the other hand each thread could have one of these objects and work independently.
I know I'm guessing what your EngineFactory might do, I hope that helps a bit.
It's not what your program can do, it's what your users do with the program.
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
subject: The application is working for single thread but not working multiple threads