Class: LogStash::Util::LazySingleton

Inherits:
Object
  • Object
show all
Defined in:
lib/logstash/util/lazy_singleton.rb

Overview

A [LazySingleton] wraps the result of the provided block, which is guaranteed to be called at-most-once, even if the block’s return value is nil.

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ LazySingleton

Returns a new instance of LazySingleton.



8
9
10
11
12
# File 'lib/logstash/util/lazy_singleton.rb', line 8

def initialize(&block)
  @mutex = Mutex.new
  @block = block
  @instantiated = false
end

Instance Method Details

#instanceObject



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/logstash/util/lazy_singleton.rb', line 14

def instance
  unless @instantiated
    @mutex.synchronize do
      unless @instantiated
        @instance = @block.call
        @instantiated = true
      end
    end
  end

  return @instance
end

#reset!Object



27
28
29
30
31
32
# File 'lib/logstash/util/lazy_singleton.rb', line 27

def reset!
  @mutex.synchronize do
    @instantiated = false
    @instance = nil
  end
end