• Post Reply Bookmark Topic Watch Topic
  • New Topic

Thread sharing local variables?

 
Avianu Sud
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A method is defined in a class that implements Thread.

If a method has local variables, and is called twice,
will the 2 invocations share the copies of the local variables? or will the local variables have their own values for each invocation of the method.

(I have an understanding that they will have their own local space)
When then will synchronization be needed?

Thanks in advance.
 
Tom Hill
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

the object bob is created everytime the method is run

The int someValue will change when method() is run on each instance of SomethingElse - method should probably be synchronized to prevent things changing the value of someValue while the other instances are using it.

Hope that helps
 
Avianu Sud
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tom, Thanks.
The example you state makes sense.

I am also asking the case where someMethod has a input parameter, and local variables. Do those need to be Threadsafe? or does each call to someMethod, has its own memory space for the local variables?


- Avi
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Each thread entring the method uses the parameter objects sent to it. If two callers send references to the same object then the two threads could get into race conditions modifying fields on the object. If the callers send different parameter objects they are safe. Almost. The callers are starting new threads and we have no idea what else they might try to do with the objects they passed as parameters. Doesn't make us feel very warm and fuzzy does it?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!