• Post Reply Bookmark Topic Watch Topic
  • New Topic

method returns before executing body  RSS feed

 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In JLS section 8.1.3.4
http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#36930
�This prevents method one and method two from being executed concurrently, and furthermore guarantees that the shared values of i and j are both updated before method one returns.�
Does this imply that without synchronization, method one could return before the expressions i++ and j++ are evaluated?
If so, would you please explain how this can happen?
 
John Smith
Ranch Hand
Posts: 2937
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Does this imply that without synchronization, method one could return before the expressions i++ and j++ are evaluated?

I assume that you are refering to this code:

Since methods one() and two() are not synchronized, it could happen that method two() will print different values of i and j. It's not that method one() will return before its completion, it's that the thread that executes method one() is put in the wait() state by the thread scheduler right after the operation i++. At that time, another thread may execute method two() thus resulting in inconsistent output where i is less that j.
Eugene.
 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
synchronization guarantees X
without synchronization, X is not guaranteed
without synchronization, not X is possible
X: values are updated before method returns
not X: values are not updated before method returns
not X: method returns and some value is not updated
without synchronization, when method returns some value is not updated
 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I figured out what was confusing me.
Before a method returns, the expressions will be evaluated and the variables in the working memory will be updated.
Without synchronization, when the method returns the variables in the shared memory might not be updated.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!