class AMQ::IntAllocator

Simple bitset-based integer allocator, heavily inspired by com.rabbitmq.utility.IntAllocator class in the RabbitMQ Java client.

Unlike monotonically incrementing identifier, this allocator is suitable for very long running programs that aggressively allocate and release channels.

Attributes

hi[R]

@return [Integer] Upper boundary of the integer range available for allocation

lo[R]

@return [Integer] Lower boundary of the integer range available for allocation

number_of_bits[R]

@return [Integer] Number of integers in the allocation range

Public Class Methods

new(lo, hi) click to toggle source

@param [Integer] lo Lower boundary of the integer range available for allocation @param [Integer] hi Upper boundary of the integer range available for allocation @raise [ArgumentError] if upper boundary is not greater than the lower one

# File lib/amq/int_allocator.rb, line 26
def initialize(lo, hi)
  raise ArgumentError.new "upper boundary must be greater than the lower one (given: hi = #{hi}, lo = #{lo})" unless hi > lo

  @hi = hi
  @lo = lo

  @number_of_bits = hi - lo
  @range          = Range.new(1, @number_of_bits)
  @free_set       = BitSet.new(@number_of_bits)
end

Public Instance Methods

allocate() click to toggle source

Attempts to allocate next available integer. If allocation succeeds, allocated value is returned. Otherwise, nil is returned.

Current implementation of this method is O(n), where n is number of bits in the range available for allocation.

@return [Integer] Allocated integer if allocation succeeded. nil otherwise.

# File lib/amq/int_allocator.rb, line 44
def allocate

  if n = @free_set.next_clear_bit

    if n < @hi - 1 then
      @free_set.set(n)
      n + 1
    else
      -1
    end

  else
    -1
  end
end
allocated?(reservation) click to toggle source

@return [Boolean] true if provided argument was previously allocated, false otherwise

# File lib/amq/int_allocator.rb, line 70
def allocated?(reservation)
  @free_set.get(reservation-1)
end
free(reservation) click to toggle source

Releases previously allocated integer. If integer provided as argument was not previously allocated, this method has no effect.

@return [NilClass] nil

# File lib/amq/int_allocator.rb, line 64
def free(reservation)
  @free_set.unset(reservation-1)
end
Also aliased as: release
release(reservation)
Alias for: free
reset() click to toggle source

Releases the whole allocation range

# File lib/amq/int_allocator.rb, line 75
def reset
  @free_set.clear
end