iahsan
iahsan

Reputation: 115

Singleton and Synchronised Servlet

I want to create a Servlet that processes input to a serial device and for that reason I want to make sure that exactly one instance of Servlet exists in the container at a time (irrespective of whether the container makes only one instance I have to make sure of it) and also the access to the serial port is either synchronised or serialised.

Any suggestions?

Upvotes: 0

Views: 219

Answers (2)

alf
alf

Reputation: 8513

Suggestion: don't do that. Leave servlet management to the container, and use your own singleton for serial port processing.

Solution: you cannot, as you have no control over constructor. What you can do, though, (and what is a Very Bad Thing—don't tell anyone I said that) is to have a static field in a servlet, keeping a reference to the first instantiated instance. This way, all the instances of the servlet will be able to delegate the processing to this very first instance.

Again, just separating request processing from serial port processing will make things much more easier for both you and the container.

Upvotes: 1

Qwerky
Qwerky

Reputation: 18435

You don't need the servlet to be a singleton, you only need to be able to control access to the serial port. In fact even if you could enforce a single instance of the servlet class, the spec enables multiple users to access the servlet concurrently.

You could instead write a class that handles access to the port, encapsulating control by only allowing a single thread to access at a time. You'd then need to decide how you wanted concurrent requests to the servlet to behave (block, return some sort of 'serial port in use' error message, etc).

Upvotes: 5

Related Questions