Class: WEBrick::Utils::TimeoutHandler

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

Overview

Class used to manage timeout handlers across multiple threads.

Timeout handlers should be managed by using the class methods which are synchronized.

id = TimeoutHandler.register(10, Timeout::Error)
begin
  sleep 20
  puts 'foo'
ensure
  TimeoutHandler.cancel(id)
end

will raise Timeout::Error

id = TimeoutHandler.register(10, Timeout::Error)
begin
  sleep 5
  puts 'foo'
ensure
  TimeoutHandler.cancel(id)
end

will print ‘foo’

Constant Summary collapse

TimeoutMutex =

Mutex used to synchronize access across threads

Mutex.new

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTimeoutHandler

Returns a new instance of TimeoutHandler.



173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/webrick/utils.rb', line 173

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

.cancel(id) ⇒ Object

Cancels the timeout handler id



167
168
169
170
171
# File 'lib/webrick/utils.rb', line 167

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

.register(seconds, exception) ⇒ Object

Registers a new timeout handler

time

Timeout in seconds

exception

Exception to raise when timeout elapsed



159
160
161
162
163
# File 'lib/webrick/utils.rb', line 159

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

Instance Method Details

#cancel(thread, id) ⇒ Object

Cancels the timeout handler id



212
213
214
215
216
217
218
219
220
221
# File 'lib/webrick/utils.rb', line 212

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

#interrupt(thread, id, exception) ⇒ Object

Interrupts the timeout handler id and raises exception



191
192
193
194
195
196
197
# File 'lib/webrick/utils.rb', line 191

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

#register(thread, time, exception) ⇒ Object

Registers a new timeout handler

time

Timeout in seconds

exception

Exception to raise when timeout elapsed



204
205
206
207
208
# File 'lib/webrick/utils.rb', line 204

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