How we can make servlet synchronized?

强颜欢笑 提交于 2019-12-30 12:03:09

问题


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.


回答1:


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




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/19509543/how-we-can-make-servlet-synchronized

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!