• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Tim Cooke
Sheriffs:
  • Rob Spoor
  • Liutauras Vilda
  • paul wheaton
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Mikalai Zaikin
  • Carey Brown
  • Piet Souris
Bartenders:
  • Stephan van Hulst

Is threadsafe and static variable/method related to each other?

 
Ranch Hand
Posts: 212
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is threadsafe and static variable/method related to each other?

I ask this question because thread-safety is important to allow access to shared resource without race conditions and static variable/method is one which is shared between objects of a class.
 
Bartender
Posts: 15720
367
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No.

Static variables are unsafe even in a single threaded application, because it's hard to predict when and from where their value will change. NEVER USE STATIC VARIABLES.
 
Saloon Keeper
Posts: 28224
198
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Absolutely No.

Neither static nor member variables are inherently thread-safe. This is true regardless of whether you have a single physical CPU core or multiple cores, since Java's multi-threading is not dependent on hardware.

The only way to make a variable or method thread-safe is to denote it as synchronized or at least (and this is more dangerous), to only access it via synchronized methods.

There are many uses for static variables, though not as many as most people think, so when Stephan says "never use static variables", I'm going to re-state that in a more qualified way:

NEVER USE STATIC VARIABLES IN AN ATTEMPT TO BE THREAD-SAFE. Because, again, they aren't.
 
What a show! What atmosphere! What fun! What a tiny ad!
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic