Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static variable/thread safe

 
Eunis Huang
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Eunis
 
Tim Duncan
Ranch Hand
Posts: 150
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nope, static vars are never thread-safe. All instances of the servlet will be able to access the static var.
 
tony lee
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
tony
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
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.
-anthony
[ March 22, 2002: Message edited by: Anthony Villanueva ]
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For completeness: static final variables are the exception., of course.
- Peter
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic