• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Method variables & Threads

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you have the following class...
public class A {
int m_i = 10;
public void method1() {
int x = 0;
x = 10;
}
}
Does method1() need to be synchronized even though it does not access any class instance variables? Asked another way: Do 2 or more threads accessing the same un-synchronized method (method1() in this case) step on eachother's toes, even if the method only uses variables local to that method? I hope I've explained it well.
Thanks,
Kyle
 
Ranch Hand
Posts: 218
VI Editor Ruby Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No you don't have to synchronized the method. Every local variables within the method are local, and during execution they have their own memory space. So different threads execution have their own stack of local variables.
 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As best I understand it, you would not need to synchronize this. Each invocation of method1() will have its own frame on the stack, which x will be contained/scoped by. However, if you were changing m_i even once in the method, you would of course need to synchronize.
 
Your mind is under my control .... your will is now mine .... read this tiny ad
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic