Skip to content

Safe final immutable objects #120

Closed
Closed
@pitr-ch

Description

@pitr-ch

this is followup to #102 discussion.

In Java if you create an object where all its fields as declared as final than the visibility of those fields is guaranteed (assuming proper construction (which means that references to it do not escape during construction)).

I am looking for a way to properly construct an object in JRuby having similar guaranty assuming any ivar won't be changed after the construction. So it would not need synchronization for every subsequent method call.

From my limited knowledge of Java and JMM I am thinking that the following should work

module GuaranteedVisibility
  require 'jruby'
  java_import 'sun.misc.Unsafe'

  constructor            = Unsafe.java_class.declared_constructor
  constructor.accessible = true
  UNSAFE                 = constructor.new_instance

  def new(*args, &block)
    super *args, &block
    # only Java8
    # http://openjdk.java.net/jeps/171
    # http://stackoverflow.com/questions/23603304/java-8-unsafe-xxxfence-instructions
    UNSAFE.store_fence
  end
end

class ACLass
  extend GuaranteedVisibility
  def initialize
    @a = 'a'
  end
end

AClass.new # guarantees visibility

The store_fence method will ensure that the store_cache on the processor core will be flushed to memory so all other cores will see the latest values. (Same can be done by writing to a volatile field on Java7.)

Metadata

Metadata

Assignees

Labels

questionAn user question, does not change the library.

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions