Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

hoisting a field out of the loop  RSS feed

 
Marilyn de Queiroz
Sheriff
Posts: 9080
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
IntelliJ contains this message ...
"This inspection reports on any instances of while loops which spin on the value of a non-volatile field, waiting for it to be changed by another thread. In addition to being potentially extremely CPU intensive when little work is done inside the loop, such loops are likely have different semantics than intended, as the Java Memory Model allows such field accesses to be hoisted out of the loop, causing the loop to never complete even if another thread does change the field's value."

I'm thinking this may be causing a problem in the current code, but I don't understand the part about "the Java Memory Model allows such field accesses to be hoisted out of the loop".

How do you hoist a field out of the loop?

 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's not something you would do; it's something the JIT compiler would do to optimize. Something like this:

That local variable is on the stack and thus can be accessed quickly compared to a field in an object on the heap. If isTerminated isn't declared as transient, or if there isn't some sort of synchronization within this method (maybe a wait-notify for example), there's no reason that the JVM is obligated to get a more up-to-date copy of the data from the heap. If some other thread changes the value of isTerminated, this thread won't necessarily know about it.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jim Yingst:
If isTerminated isn't declared as transient


Huh? Did you mean "volatile", or does "transient" have some additional thread-related behaviour, of which I am not aware?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, I meant volatile. Thanks.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!