Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

local (stack-based) variable vs shared across threads  RSS feed

 
Marie Day
Greenhorn
Posts: 29
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How can I tell that a variable is local (stack-based) and doesn't require synchronization?

I'm reading Java Concurrency In Practice by Brian Goetz, and I need clarification on an example in the book. The text says: "The portions of code that are outside the synchronized blocks operate exclusively on local (stack-based) variables, which are not shared across threads and therefore do not require synchronization."
I'm looking at the listing, and I don't understand, for instance, why



doesn't require synchronization, but



does require synchronization.

Both of those lines seem "local" to me. Could someone explain how I can see from looking at the code why the synchronization was placed where it was?
The word synchronized appears on lines 9, 10, 17 and 27. (I tried to bold the word synchronization, but the tags show, for some reason, and no bolding.)

This is on page 31:


 
Henry Wong
author
Sheriff
Posts: 22841
119
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Marie Day wrote:
Both of those lines seem "local" to me. Could someone explain how I can see from looking at the code why the synchronization was placed where it was?


From the context, it looks like "local" means using local variables, which is clearly defined in Java... Also, Java doesn't have a definition of "seems local", so don't know what you mean by that. And of course, local variables don't need synchronization.

To speculate on your followup question... First, local reference variables are local; they can't be shared by multiple threads, and hence, don't need synchronization. The objects that these variables refer to may shared by multiple threads and may need synchronization.

Henry
 
Marie Day
Greenhorn
Posts: 29
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need to find and review a definition of "local variable."
 
Henry Wong
author
Sheriff
Posts: 22841
119
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Marie Day wrote:I need to find and review a definition of "local variable."


The Oracle Java tutorial on variables may be a good place to start...

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html

Henry
 
Marie Day
Greenhorn
Posts: 29
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!