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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With