Midnight Blue
Midnight Blue

Reputation: 5141

Thread-safety issue for servlet

I recently read an article about writing thread-safe servlets, and I learned that it is unsafe to make use of a servlet's member fields in doGet() and doPost() methods since it is likely that the single instance of servlet handles two separate requests with two threads, meaning the member variables are shared resource. I am wondering if I have to worry about thread-safety on servlet dependencies. In my application design, the servlet will make a service call to a POJO service handler, and I am thinking of a single dependency injection from Spring(using ApplicationContext.getBean()). Thanks in advance.

Upvotes: 2

Views: 1528

Answers (2)

fdreger
fdreger

Reputation: 12495

Being thread-safe is exactly the reason why you have the 'request' scope. Making things thread-safe is much harder than it looks. But in a common web scenario you can push the problem all the way down to:

  • database, which gives you atomicity and thread safety for free;
  • stateless services, which are, by definition, thread-safe (there is no state that could be broken).

So just:

  • make your daos stateless,
  • make your services stateless,
  • if you need some temporary state, use request-scoped beans.

getBean() is thread-safe, so you can just pluck your pojo services and use them, as long as you do not store them as servlet attributes.

In such case your only problems are:

  • beans living in session;
  • custom caches;
  • complicated custom application logic;

Beans living in sessions can be made immutable (unless points 2 or 3 also apply). Custom caches can usually be skipped (In many cases they do not make things faster anyway - really! Unless you can prove them useful by profiling, throw them away). This leaves us with number 3: complicated custom application logic. And this one is tricky.

Anyway, since such application logic is inherently complicated, being thread-safe is probably the least of our worries.

Upvotes: 2

Anon
Anon

Reputation: 1330

Yes you have to worry about it on the POJO as well. It's a member variable. Make the service threadsafe.

Upvotes: 4

Related Questions