File: safe_initialization.rb

package info (click to toggle)
ruby-concurrent 1.3.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,136 kB
  • sloc: ruby: 30,875; java: 6,128; ansic: 265; makefile: 26; sh: 19
file content (36 lines) | stat: -rw-r--r-- 1,123 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
require 'concurrent/synchronization/full_memory_barrier'

module Concurrent
  module Synchronization

    # @!visibility private
    # @!macro internal_implementation_note
    #
    # By extending this module, a class and all its children are marked to be constructed safely. Meaning that
    # all writes (ivar initializations) are made visible to all readers of newly constructed object. It ensures
    # same behaviour as Java's final fields.
    #
    # Due to using Kernel#extend, the module is not included again if already present in the ancestors,
    # which avoids extra overhead.
    #
    # @example
    #   class AClass < Concurrent::Synchronization::Object
    #     extend Concurrent::Synchronization::SafeInitialization
    #
    #     def initialize
    #       @AFinalValue = 'value' # published safely, #foo will never return nil
    #     end
    #
    #     def foo
    #       @AFinalValue
    #     end
    #   end
    module SafeInitialization
      def new(*args, &block)
        super(*args, &block)
      ensure
        Concurrent::Synchronization.full_memory_barrier
      end
    end
  end
end