Win a copy of TensorFlow 2.0 in Action this week in the Artificial Intelligence and Machine Learning forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Paul Clapham
  • Bear Bibeault
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • salvin francis
  • Scott Selikoff
  • fred rosenberger

Threads and local variables

 
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.
 
author
Posts: 23887
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux 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
 
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
 
(instanceof Sidekick)
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 !!

 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic