• Post Reply Bookmark Topic Watch Topic
  • New Topic

Threading in Java  RSS feed

 
PN Kumar
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When we have a static method which is not synchronized, it is possible that two or more threads would access the same method at the same time. At this point of time, are there going to be two copies of the same method - one for each thread?If not, what would happen to the local variables? Or is it that each thread would have its own stack where local variables would be placed?If so, what would happen to the static variables? Any light on this is appreciated.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The local variables for any method, static or not, are held on the execution stack of the thread that's executing it. If a hundred threads call a method simultaneously, then there will be a hundred "copies" of the local variables.
On the other hand, there is a copy of a class's member variables in each instance of the class, and there is just a single copy of the static variables for a class.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to the Threads and Synchronization forum.
 
PN Kumar
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What would happen to the static variables -> there being a single variable for the whole class, if 2 threads modify its value differently -> how would the value of the static variable be affected?
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Depends on the way in which they modify the variable.
Fundamentally though it is indeterminate, or unpredictable. Its a bad thing and you should not do it.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!