File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Web Component Certification (SCWCD/OCPJWCD) and the fly likes static variable/thread safe Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Web Component Certification (SCWCD/OCPJWCD)
Bookmark "static variable/thread safe" Watch "static variable/thread safe" New topic

static variable/thread safe

Eunis Huang

Joined: Feb 11, 2002
Posts: 5
If a servlet does NOT implement SingleThreadModel, then the static variable in this servlet is thread safe, otherwise, (if implement SingleThreadModel) the static varialbe is not thread safe.
Is it right or not?
Thank guys.
Tim Duncan
Ranch Hand

Joined: Aug 20, 2001
Posts: 150
Nope, static vars are never thread-safe. All instances of the servlet will be able to access the static var.
tony lee
Ranch Hand

Joined: Jan 21, 2002
Posts: 52
hi eunis,
a static variable still can be accessed by different thread by declaring var.ClassName. if you can tell the difference between a static and a non-static, you'll find static variable is the same as a non-static in thread safty senario.

Anthony Villanueva
Ranch Hand

Joined: Mar 22, 2002
Posts: 1055
By default, a servlet normally has only one servlet instance per servlet definition. Even if we assume or guarantee that only one servlet instance is available to service requests, concurrent requests will spawn multiple threads, so static servlet variables are not thread-safe.
A servlet that implements SingleThreadModel is usually pooled by the container so this situation is not thread-safe for static servlet variables either.
[ March 22, 2002: Message edited by: Anthony Villanueva ]
Peter den Haan
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
For completeness: static final variables are the exception., of course.
- Peter
I agree. Here's the link:
subject: static variable/thread safe
jQuery in Action, 3rd edition