Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread-safe servlets

 
kri shan
Ranch Hand
Posts: 1478
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since SingleThreadModel is deprecated from Servlets 2.4, only option for thread-safe is synchronized. Can i make service method as synchronized(particular code block synchronization is efficient)?
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65225
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, that would be very inefficient.

Why do you feel you need to do this? Why not just write your servlets correctly (thread-safely) in the first place?
 
kri shan
Ranch Hand
Posts: 1478
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why not just write your servlets correctly (thread-safely) in the first place?

Hi Bear, How do write servlets correctly (thread-safely) without using synchronized block?
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65225
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What do you feel that you need to synchronize?

Are you using instance variables in the servlets? If so, you should not be.
 
Ulf Dittmer
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, avoiding instance variables alone won't generally do the trick, since there's usually shared state involved somewhere (whether it's in the application context or in some global static fields). So the question about synchronization is justified. But as pointed out, the proper approach is not to synchronize methods, but to synchronize those code blocks that access the shared state (or to use locks, or any of the other facilities in java.util.concurrent).

If you're serious about concurrency -and in these days of multi-core CPUs, multi-CPU machines, and multi-request servers, which developer can afford not to be?- do yourself a favor and get one of the eminent books on the subject, either by Oaks/Wong or by Brian Goetz et al. Handling concurrency well without killing performance while making efficient use of Java's many features in this area is not easy to pick up otherwise.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65225
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, that's why I asked for clarification. 99% of the time, it's instance variables causing any threading problems, but there are the other potential problem areas.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic