Forcing J2EE Servlets to be single-threaded?

I’m doing some code conversion to J2EE compatibilty, and some classes require that they be executed with the guarantee only one outstanding thread is ever accessing them. They can process incoming requests asynchronously, by queuiing them up. They use a very fine-grained asynch exec model, so that all this happens efficiently (think of DMA…).

This is problematic, since J2EE doesn’t (IIRC) allow single-thread-only access to any servlet, which means I will have to jump through hoops within the servlet to try and guarantee it - throw exceptions in constructors to try and prevent the things being created - etc. I’ve never tried to do this in J2EE that I can remember, so maybe there’s some simple way I’m just ignorant of.

These classes work fine in the grexengine (which just has a flag to enable this for a given component!), but rather than have to port or rewrite the code to make it also execute under J2EE I’d like to find some clean way of making it work. Any ideas?

PS: the best hack I can think of so far is:

  1. Have a single static variable which is some object.
  2. Have the main service() method of the servlet wait() on that object’s monitor
  3. When servicing is complete, notify()

So, I will have some (possibly huge depending upon how crap the J2EE container is) number of instances of each servlet, but they will be stuck on monitors and only one will be allowed to execute at once. My experience of monitors these days is that they’re fast enough that this should not impact performance too much even under high load

…but life would be much easier if there were some feature in J2EE that I could invoke to prevent this wasteful blocking :(.

The Servlet specification defines the following interface for single threaded servlets

SingleThreadServlet

Any servlet that implements this interface (it’s a marker interface so no methods need defining), is guaranteed to be thread safe.

http://www.unix.org.ua/orelly/java-ent/servlet/ch03_04.htm

Andy.

Thanks. I knew about STS, but it only goes halfway to what I want - it doesn’t prevent additional instances from being created - although I was being dumb in not thinking of using that instead of monitors. I’ll still need to make everything static :frowning: but it’s better than nothing.

I don’t know what exactly you want to do in your servlet; I think you use it like a door for some kind of service call.
So, if this is your environment, maybe you can use a service locator.
You may use Spring like service locator in your web app (service class is singleton by default in Spring).
Your servlets get the service instance from Spring, and it serve to you a shared instance.
It is not important that your servlet is a singleton instance, isn’t his nature; move logic in external class, outside the J2EE behavior, and maybe you get the point.