Java – Singleton servlet


If I declare a singleton servlet like

public static class SomeServlet extends HttpServlet {…..

It gives the error indicating that modifier static not allowed here in NetBeans.

Please let me know how to create a singleton servlet which allows only one client at a time to execute.

Thanks in Advance,

Best Solution

  • static has nothing to do with being executed by only one thread at any point in time.
  • you can have static classes as inner classes, but this doesn't help your problem due to the first point
  • If I recall correctly there's only one servlet instantiated ever, so there's no need to create singletons. Update: I didn't remember correctly as DefLog pointed out
  • therefor synchronize on a method (doGet, doPost, service or your implementation method) update: will not do the trick.

Based on your demonstrated understanding of the problem (no pun intended) I doubt that this is the solution you should be choosing. Rather rephrase your question so that you state the problem you're trying to solve with the solution you have stated in your first revision of the question.

Update: See the comments to this answer for why you really don't want to fall for synchronized. You might (for example) want to have multiple servlets accessing the same functionality one at a time. Plus you'd introduce severe scaling problems if you synchronize on a servlet level. It's definitely the wrong place for solving concurrency problems.