Class: Thread

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby-threading-toolkit/thread.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.new_with_exception_handling(handler, logger = nil, severity = :fatal, title = nil, inspect_method = :inspect_with_backtrace, *args) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/ruby-threading-toolkit/thread.rb', line 26

def self.new_with_exception_handling(handler, logger = nil, severity = :fatal, title = nil, inspect_method = :inspect_with_backtrace, *args)
  Thread.new do
    begin
      Thread.current[:title] = title
      Thread.current[:started_at] = Time.now
      yield(*args)
    rescue Exception => exception
      begin
        exception.log!(logger, severity, title, inspect_method) if logger
        handler.call(exception) if handler
      rescue Exception => handler_exception
        handler_exception.log!(logger, severity, title, inspect_method) if logger
      end
    end
  end
end

Instance Method Details

#inspect_with_valuesObject



58
59
60
# File 'lib/ruby-threading-toolkit/thread.rb', line 58

def inspect_with_values
  inspect[0..-2] + " " + keys.collect{|key| ":#{key}=>#{self[key].inspect rescue "CAN NOT INSPECT!"}"}.join(" ") + ">"
end

#join_and_terminate(timeout = 60, raise_timeout = nil) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/ruby-threading-toolkit/thread.rb', line 43

def join_and_terminate(timeout = 60, raise_timeout = nil)
  raise_timeout = timeout * (timeout > 30 ? 0.1 : 0.2) unless raise_timeout
  
  unless join(timeout)
    self.raise(ThreadJoinTimeoutExpiresError, "#{timeout} seconds join timeout expires")
    begin
      unless join(raise_timeout)
        Kernel.raise(ThreadNotTerminatedError, "Thread are not terminated after #{timeout} seconds join timeout and #{raise_timeout} seconds raise timeout")
      end
    rescue ThreadJoinTimeoutExpiresError => exception
      Kernel.raise(ThreadTerminatedError, "Thread terminated after #{timeout} seconds with force raise of ThreadJoinTimeoutExpiresError exception")
    end
  end
end