Reputation: 492
I am working on a servlet and i want to make my servlet synchronized.So please any can help me that how it can be possible.
Upvotes: 1
Views: 10989
Reputation: 2288
Making a servlet synchronized is really a bad design. You cannot handle more that one client at a time. I suggest you to make a block of code synchronized if you want some part of your code to be thread-safe. Please do have a look to here
Upvotes: 1
Reputation: 8820
Anytime you synchronize blocks of code, you introduce bottlenecks into your system. When you synchronize a code block, you tell the JVM that only one thread may be within this synchronized block of code at a given moment. If we run a multithreaded application and a thread runs into a synchronized code block being executed by another thread, the second thread must wait until the first thread exits that block.
It is important to accurately identify which code block truly needs to be synchronized and to synchronize as little as possible.
Note that you need not (and should not) synchronize on local data or parameters. And especially you shouldn't synchronize the service() method! (Or doPost(), doGet() etc.)
What's a better approach for enabling thread-safe servlets ? SingleThreadModel Interface or Synchronization?
Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading.
Also, note that SingleThreadModel is pretty resource intensive from the server's perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free - which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool.
Upvotes: 2
Reputation: 12880
Making a servlet synchronized is a very bad design. The main purpose of it will be destroyed. Servlets should be designed in such a way that it can process multiple number of requests simultaneously! Moreover, the servlet should not contain any state storage and press the need for synchronization. Please rethink your design
Upvotes: 3