class ZMQ::ManagedMessage

A subclass of #Message that includes finalizers for deallocating native memory when this object is garbage collected. Note that on certain Ruby runtimes the use of finalizers can add 10s of microseconds of overhead for each message. The convenience comes at a price.

The constructor optionally takes a string as an argument. It will copy this string to native memory in preparation for transmission. So, don't pass a string unless you intend to send it. Internally it calls copy_in_string.

Call close to release buffers when you have not passed this on to Socket#send. That method calls close on your behalf.

When you are done using a received message object, just let it go out of scope to release the memory. During the next garbage collection run it will call the equivalent of #LibZMQ.zmq_msg_close to release all buffers. Obviously, this automatic collection of message objects comes at the price of a larger memory footprint (for the finalizer proc object) and lower performance. If you wanted blistering performance, Ruby isn't there just yet.

As noted above, for sent objects the underlying library will call close for you.

Private Class Methods

close(ptr) click to toggle source

Message finalizer Note that there is no error checking for the call to zmq_msg_close. This is intentional. Since this code runs as a finalizer, there is no way to catch a raised exception anywhere near where the error actually occurred in the code, so we just ignore deallocation failures here.

# File lib/ffi-rzmq/message.rb, line 283
def self.close ptr
  Proc.new do
    # release the data buffer
    LibZMQ.zmq_msg_close ptr
  end
end

Public Instance Methods

close() click to toggle source

Manually release the message struct and its associated data buffer.

Calls superclass method ZMQ::Message#close
# File lib/ffi-rzmq/message.rb, line 261
def close
  rc = super()
  remove_finalizer
  rc
end
copy_in_bytes(bytes, len) click to toggle source

Makes a copy of len bytes from the ruby string bytes. Library handles deallocation of the native memory buffer.

Calls superclass method ZMQ::Message#copy_in_bytes
# File lib/ffi-rzmq/message.rb, line 249
def copy_in_bytes bytes, len
  rc = super(bytes, len)

  # make sure we have a way to deallocate this memory if the object goes
  # out of scope
  define_finalizer
  rc
end

Private Instance Methods

define_finalizer() click to toggle source
# File lib/ffi-rzmq/message.rb, line 270
def define_finalizer
  ObjectSpace.define_finalizer(self, self.class.close(@pointer))
end
remove_finalizer() click to toggle source
# File lib/ffi-rzmq/message.rb, line 274
def remove_finalizer
  ObjectSpace.undefine_finalizer self
end