Class: WEBrick::Utils::TimeoutHandler

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/webrick/utils.rb

Constant Summary

TimeoutMutex =
Mutex.new

Class Method Summary (collapse)

Instance Method Summary (collapse)

Methods included from Singleton

__init__, #_dump, #clone, #dup

Constructor Details

- (TimeoutHandler) initialize

A new instance of TimeoutHandler



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/webrick/utils.rb', line 121

def initialize
  @timeout_info = Hash.new
  Thread.start{
    while true
      now = Time.now
      @timeout_info.each{|thread, ary|
        ary.dup.each{|info|
          time, exception = *info
          interrupt(thread, info.object_id, exception) if time < now
        }
      }
      sleep 0.5
    end
  }
end

Class Method Details

+ (Object) cancel(id)



115
116
117
118
119
# File 'lib/webrick/utils.rb', line 115

def TimeoutHandler.cancel(id)
  TimeoutMutex.synchronize{
    instance.cancel(Thread.current, id)
  }
end

+ (Object) register(seconds, exception)



109
110
111
112
113
# File 'lib/webrick/utils.rb', line 109

def TimeoutHandler.register(seconds, exception)
  TimeoutMutex.synchronize{
    instance.register(Thread.current, Time.now + seconds, exception)
  }
end

Instance Method Details

- (Object) cancel(thread, id)



151
152
153
154
155
156
157
158
159
160
# File 'lib/webrick/utils.rb', line 151

def cancel(thread, id)
  if ary = @timeout_info[thread]
    ary.delete_if{|info| info.object_id == id }
    if ary.empty?
      @timeout_info.delete(thread)
    end
    return true
  end
  return false
end

- (Object) interrupt(thread, id, exception)



137
138
139
140
141
142
143
# File 'lib/webrick/utils.rb', line 137

def interrupt(thread, id, exception)
  TimeoutMutex.synchronize{
    if cancel(thread, id) && thread.alive?
      thread.raise(exception, "execution timeout")
    end
  }
end

- (Object) register(thread, time, exception)



145
146
147
148
149
# File 'lib/webrick/utils.rb', line 145

def register(thread, time, exception)
  @timeout_info[thread] ||= Array.new
  @timeout_info[thread] << [time, exception]
  return @timeout_info[thread].last.object_id
end