aspose file tools*
The moose likes Servlets and the fly likes Thread-safe servlets Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Thread-safe servlets" Watch "Thread-safe servlets" New topic
Author

Thread-safe servlets

kri shan
Ranch Hand

Joined: Apr 08, 2004
Posts: 1376
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

Joined: Jan 10, 2002
Posts: 61237
    
  66

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?


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
kri shan
Ranch Hand

Joined: Apr 08, 2004
Posts: 1376
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

Joined: Jan 10, 2002
Posts: 61237
    
  66

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
Marshal

Joined: Mar 22, 2005
Posts: 41905
    
  63
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.


Ping & DNS - my free Android networking tools app
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61237
    
  66

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Thread-safe servlets