diff --git a/src/org/zeromq/ZMQ.java b/src/org/zeromq/ZMQ.java index 5f53ccb..e074f5b 100755 --- a/src/org/zeromq/ZMQ.java +++ b/src/org/zeromq/ZMQ.java @@ -710,6 +710,20 @@ public class ZMQ { * @return the index identifying this Socket in the poll set. */ public int register (Socket socket, int events) { + //if free slot is present in the middle + if(!freeSlots.isEmpty()) { + //then use it + int free = freeSlots.remove(); + + this.sockets[free] = socket; + this.events[free] = (short)events; + + //increment actual size of elements to poll + asize++; + + return free; + } + //or else use next available slot if (this.next >= this.size) { // Compute new size for internal arrays. int nsize = this.size + SIZE_INCREMENT; @@ -735,10 +749,34 @@ public class ZMQ { this.sockets [this.next] = socket; this.events [this.next] = (short) events; + + asize++; + return this.next++; } /** + * Unregisters a Socket for polling on the specified events. + * @param socket + * the Socket to be unregistered + */ + public void remove (Socket socket) { + //find the given socket and remove it + for(int i = 0; i < this.next; ++i) { + if(this.sockets[i] == socket) { + this.sockets[i] = null; + this.events[i] = 0; + this.revents[i] = 0; + + freeSlots.add(i); + asize--; + + break; + } + } + } + + /** * Get the socket associated with an index. * * @param index @@ -832,7 +870,7 @@ public class ZMQ { for (int i = 0; i < this.next; ++i) { this.revents [i] = 0; } - return run_poll (this.next, this.sockets, this.events, this.revents, tout); + return run_poll (this.asize, this.sockets, this.events, this.revents, tout); } /** @@ -931,9 +969,12 @@ public class ZMQ { private long timeout = -2; // mark as uninitialized private int size = 0; private int next = 0; + private int asize = 0; //actual elements to poll private Socket [] sockets = null; private short [] events = null; private short [] revents = null; + //when socket is removed from polling, free slots are stored here + private java.util.LinkedList freeSlots = new java.util.LinkedList(); private static final int SIZE_DEFAULT = 32; private static final int SIZE_INCREMENT = 16;