• Post Reply Bookmark Topic Watch Topic
  • New Topic

Threads and local variables

 
Carlos G�mez
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ranchers

why the local variables are thread safe ??

Thanks in advance.
 
Henry Wong
author
Sheriff
Posts: 22516
109
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
bala nannaka
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Carlos G�mez
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yeah, thank you ranchers !!

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!