This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Say I have a servlet called TheServlet that uses non-servlet class named TheDatabase, whose job it is to query a database and return a String based on some query. Something like this:
When it comes to multi thread and synchronization issues, I think I probably have to lock access to the session object, as well as the instance object theDatabase. But to prevent multithreading issues with theDatabase instance, is using the synchronized keyword the only way to handle this, or is there a better way to design this. For example, making TheDataBase a local variable in the doPost method (instead of an instance variable), or even taking the code from TheDatabase class and sticking it in the doPost method itself. Thanks for taking the time to read this question.
Thanks for the response Bear..and thats a good question! The short answer is that I like to live dangerously---I also run with scissors...actually, its inexperience. I was trying to think of an example (in this case the fictional TheDatabase class) whose setup/initialization might take longer or be complicated, and therefore you might only want to call the constructor TheDatabase() once when the servlet is originally created? But I'm guessing by your response that an instance variable brings more problems than its worth. So, I guess the answer is, use local variables? [ April 07, 2008: Message edited by: al langley ]
But I'm guessing by your response that an instance variable brings more problems than its worth.
Absolutely. Most experienced web developers would never entertain read/write instance variables to solve the problem you state. Rather, a single instance of the "expensive" class would be created and stored in application context. Of course, because it is shared, synchronization is necessary when read/write access could cause threading issues. But instance variables? No.