Sha256: 63eb283a10cbc8e8cdc0313414b97eb1b17c03d66f8e16b3039ce0395850e90b

Contents?: true

Size: 1 KB

Versions: 6

Compression:

Stored size: 1 KB

Contents

# frozen_string_literal: true

module Datadog
  module Utils
    # Helper class to execute something only once such as not repeating warning logs, and instrumenting classes
    # only once.
    #
    # Thread-safe when used correctly (e.g. be careful of races when lazily initializing instances of this class).
    #
    # Note: In its current state, this class is not Ractor-safe.
    # In https://github.com/DataDog/dd-trace-rb/pull/1398#issuecomment-797378810 we have a discussion of alternatives,
    # including an alternative implementation that is Ractor-safe once spent.
    class OnlyOnce
      def initialize
        @mutex = Mutex.new
        @ran_once = false
      end

      def run
        @mutex.synchronize do
          return if @ran_once

          @ran_once = true

          yield
        end
      end

      def ran?
        @mutex.synchronize { @ran_once }
      end

      private

      def reset_ran_once_state_for_tests
        @mutex.synchronize { @ran_once = false }
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
ddtrace-0.51.1 lib/ddtrace/utils/only_once.rb
ddtrace-0.51.0 lib/ddtrace/utils/only_once.rb
ddtrace-0.50.0 lib/ddtrace/utils/only_once.rb
ddtrace-0.49.0 lib/ddtrace/utils/only_once.rb
ddtrace-0.48.0 lib/ddtrace/utils/only_once.rb
ddtrace-0.47.0 lib/ddtrace/utils/only_once.rb