| Author |
Threads and local variables
|
Carlos G�mez
Ranch Hand
Joined: Sep 06, 2006
Posts: 56
|
|
Hi ranchers why the local variables are thread safe ?? Thanks in advance.
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16811
|
|
Originally posted by Carlos G�mez: Hi ranchers why the local variables are thread safe ?? Thanks in advance.
Local variables are private to the method -- every method calls gets their own copy. Hence, every thread that calls a method, will get their own copy. Note: they may *not* be thread safe. It is possible to assign an object reference (that is a local variable) to a shared object. While changing the local reference variable is threadsafe, changing the shared object that it refers to, may not be. Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
bala nannaka
Ranch Hand
Joined: Apr 02, 2007
Posts: 49
|
|
|
Every thread is associated with one thread context . that is nothing but a stack .in which all the local variables are stored.so every thread has its own thread context so there is a no problem for thread safety
|
 |
Stan James
(instanceof Sidekick)
Ranch Hand
Joined: Jan 29, 2003
Posts: 8791
|
|
Let's open up Henry's point with a couple examples. Here the local variable map is pretty safe because we create the map locally, use it locally and don't let anybody else see it. But in the next one, we don't know who else might be using the map object. The object that passed it in to us may be using it on another thread. So just assigning it to a local variable won't help make it safe. And in this next one, we expose the map to somebody else who might do something unsafe with it: So a local variable is only safe if we keep it local.
|
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
|
 |
Carlos G�mez
Ranch Hand
Joined: Sep 06, 2006
Posts: 56
|
|
yeah, thank you ranchers !!
|
 |
 |
|
|
subject: Threads and local variables
|
|
|