How to avoid race condition
What are the best ways to avoid race conditions in jsp at the same time not to slow down the process.I have tried isThreadSa开发者_如何学运维fe=false synchronized(session)
however is there any other alternate solution is available?
A one-size-fits-all solution (e.g. threadSafe=false
) causes requests to be executed one at a time. And that inevitably slows down request processing.
To that avoid that scenario, you need to understand why you are getting race conditions and (re-)design your architecture to avoid the problem. For example:
if the race condition is in updates to some shared in-memory data structures, you need to synchronize access and updates to the data structure at the appropriate level of granularity
if the race condition is in updates to the your database, you need to restructure your SQL to use transactions at the appropriate level of granularity.
These are just (possible) schemas for how to solve your race condition problems. In reality, you have to understand the root causes yourself.
It depends on why you have race conditions.
The simplest thought is to have no global variables that you write to.
Do all of your logic in methods that only use local variables.
Don't have any java code in your jsp page, but call out to a bean to do the operations.
What are you doing that is causing a race condition?
isThreadSafe=false
This will probably lead to poor performance as it makes page access sequential. It also will only affect one page, so if you access the data via another page, this will do nothing for you.
synchronized(session)
This is not guaranteed to work (though it will on some servers as a side-effect of the implementation).
Any solution will probably require more information about the data you are trying to guard and the configuration of your server.
精彩评论