Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing class variables from methods using extra local variables

Tags:

java

I was reading the ArrayBlockingQueue implementation code another day by Doug Lea and noticed a lot of methods (public, default, and private) have the following references:

final Object[] items = this.items;
final ReentrantLock lock = this.lock;

I have asked around to have a reasonable explanation but so far no satisfactory answers. I am not quite sure why we need to have such local variables in the first place? And what is the benefit(s) of coding this way?

Maybe I missed some important points in concurrent programming. Could you please help to shed some lights on this?

like image 301
victor yao Avatar asked Mar 04 '23 14:03

victor yao


2 Answers

A very good reason for a method to set a local variable to the value of an accessible class or instance variable, or a value accessible through one of those, is to thereafter be independent of any modifications to that variable by other threads. With some caveats, this allows the method that needs to access that value more than once to perform a consistent computation reflecting the state of the host object at some specific point in time, even if that state has changed by the time the result is returned. This is likely what's happening in the code you have been studying.

like image 86
John Bollinger Avatar answered Mar 08 '23 15:03

John Bollinger


It happened that I just came across this link which explained some of the main arguments of coding this way:[In ArrayBlockingQueue, why copy final member field into local final variable?. Please read it to understand more, instead, I am hoping of not getting more confused. I believe it helps you to look at this practice from another angle. It seems it at least met some of my curiosities around this coding style.

like image 42
victor yao Avatar answered Mar 08 '23 17:03

victor yao