[zeromq-dev] Java bindings error?

Joe Holloway jholloway7 at gmail.com
Thu Jun 24 00:50:34 CEST 2010


Hi Martin,

On Wed, Jun 23, 2010 at 12:56 PM, Martin Sustrik <sustrik at 250bpm.com> wrote:
>
> Hi Stuart,
>
> >> Is it possible that garbage collector destroys the context object even
> >> though there are still sockets open?
> >
> > Yes, but the by far most likely scenario here is that there is a bug in the native part of jzmq (as opposed to the JVM).
>
> What I meant was that context is created, then used to create the socket
> and afterwards it's not used any more. Can that result in gc destroying
> it after the socket creation but before the program ends?

I think you are on the right track.  Looking at the native jzmq code,
it appears that transiently using a Context object to construct
Sockets would allow the JVM to "finalize" the Context object while the
application still has a live reference to the Socket object(s).
Something like this:

class SocketBuilder {
   public ZMQ.Socket build() {
       ZMQ.Context ctx = new ZMQ.Context(...);

       // Transiently use context to construct socket

       return ctx.socket(...);
   }  // ctx is now eligible for gc
}

// Elsewhere in the application ...

ZMQ.Socket socket = new SocketBuilder().build();

// ...
// Eventually GC will happen and finalize Context
// even though we still have a good socket reference
// ...

JNI provides a way for the native code to acquire a "phantom
reference" [1] to help in this situation (never used it, but I assume
this is what it's for). The JNI Socket::construct(...) method could
acquire a reference to the Context object to essentially force their
lifespans to be the same.  Or, I recall seeing some reference counting
internal to 0MQ that could maybe be put to use to make sure the native
context object isn't destroyed until all of it's sockets are
destroyed.

A quick workaround would be to ensure that the managed Context and
Socket objects have the same lifespan in the application code.

P.S. Stuart, is your work in this space related to Clojure?

[1] http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ref/PhantomReference.html



More information about the zeromq-dev mailing list