my dog learned polymorphism
The moose likes Beginning Java and the fly likes thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "thread" Watch "thread" New topic


Ramm Kummar

Joined: Feb 10, 2009
Posts: 26
Why local variables are thread safe while instance variables are not?
Marco Ehrentreich
best scout

Joined: Mar 07, 2007
Posts: 1294

Hi Ramm,

in short instance variables are shared among all threads accessing the same object. In contrast local variables are stored within a stack frame which is created for each method call. For this every thread calling a method gets its own copy of a local variable and can't interfere with other threads this way. Of course multi-threading is a lot more complicated but this is the basic difference between instance variables and local variables.

wood burning stoves
subject: thread
It's not a secret anymore!