Sha256: 6df5dc40eb5e8785a062e2a5ab7b668d8b1f8e7f6d96071022b3313660a0a456

Contents?: true

Size: 1.56 KB

Versions: 14

Compression:

Stored size: 1.56 KB

Contents

# frozen_string_literal: true

module Karafka
  module Helpers
    # Allows a given class to run async in a separate thread. Provides also few methods we may
    # want to use to control the underlying thread
    #
    # @note Thread running code needs to manage it's own exceptions. If they leak out, they will
    #   abort thread on exception.
    module Async
      # Mutex used to ensure we do not create multiple threads if we decide to run this
      # in parallel on multiple threads
      MUTEX = Mutex.new

      private_constant :MUTEX

      class << self
        # Adds forwardable to redirect thread-based control methods to the underlying thread that
        # runs the async operations
        #
        # @param base [Class] class we're including this module in
        def included(base)
          base.extend ::Forwardable

          base.def_delegators :@thread, :join, :terminate, :name
        end
      end

      # @return [Boolean] true if thread is present and is running, false otherwise
      def alive?
        MUTEX.synchronize do
          return false unless @thread

          @thread.alive?
        end
      end

      # Runs the `#call` method in a new thread
      # @param thread_name [String] name that we want to assign to the thread when we start it
      def async_call(thread_name)
        MUTEX.synchronize do
          return if @thread&.alive?

          @thread = Thread.new do
            Thread.current.name = thread_name

            Thread.current.abort_on_exception = true

            call
          end
        end
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
karafka-2.4.17 lib/karafka/helpers/async.rb
karafka-2.4.16 lib/karafka/helpers/async.rb
karafka-2.4.15 lib/karafka/helpers/async.rb
karafka-2.4.14 lib/karafka/helpers/async.rb
karafka-2.4.13 lib/karafka/helpers/async.rb
karafka-2.4.12 lib/karafka/helpers/async.rb
karafka-2.4.11 lib/karafka/helpers/async.rb
karafka-2.4.10 lib/karafka/helpers/async.rb
karafka-2.4.9 lib/karafka/helpers/async.rb
karafka-2.4.8 lib/karafka/helpers/async.rb
karafka-2.4.7 lib/karafka/helpers/async.rb
karafka-2.4.6 lib/karafka/helpers/async.rb
karafka-2.4.5 lib/karafka/helpers/async.rb
karafka-2.4.4 lib/karafka/helpers/async.rb