Issue #12021 has been updated by Petr Chalupa.


The above declares the final variables explicitly, there is also an alternative approach to threat all instance variable assignments in constructor as a final variable. Therefore protecting them implicitly, ensuring their visibility after the object is constructed. If one of the instance variables is reassigned later it will loose any visibility guaranties. This has to be explored more deeply though. The actual cost of having the protection always on implicitly has to be determined.

----------------------------------------
Feature #12021: Final instance variables
https://bugs.ruby-lang.org/issues/12021#change-56657

* Author: Petr Chalupa
* Status: Open
* Priority: Normal
* Assignee: 
----------------------------------------
Having a final instance variables in Ruby will allow: to construct thread-save immutable objects without additional synchronisation on instance variable reading

~~~ ruby
# Immutable and thread-safe 
class TreeNode
  attr :left, :right, :value, final: true
  attr_reader :left, :right, :value

  def initialize(left, right, value)
    @left, @right, @value = left, right, value
  end
end
~~~

And to fix the an issue shown in the following example:

~~~ ruby
attr :lock, final: true
def initialize
  @lock = Mutex.new
  # ...
end  
   
def a_protected_method
  @lock.synchronize do
    # ...
  end
end
~~~

The issue lies in initialization of instance variable `@lock` which is not ensured to be visible in subsequent call to `a_protected_method` method on a different thread.

Summary can be found in this document https://docs.google.com/document/d/1c07qfDArx0bhK9sMr24elaIUdOGudiqBhTIRALEbrYY/edit#.

The aggregating issue of this effort can be found [here](https://bugs.ruby-lang.org/issues/12019).



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>