add request management
[jSite2.git] / src / net / pterodactylus / jsite / core / NodeManager.java
index fe52fd7..70da6d6 100644 (file)
@@ -337,6 +337,56 @@ public class NodeManager implements HighLevelClientListener {
                return Collections.unmodifiableList(nodes);
        }
 
+       /**
+        * “Borrows” a high-level client for the given node. A borrowed client
+        * <strong>has</strong> to be returned to the node manager using
+        * {@link #returnHighLevelClient(HighLevelClient)} when it is no longer in
+        * use, i.e. after a message has been sent! This method will block until a
+        * high-level client for the given node is available.
+        * 
+        * @param node
+        *            The node to get a high-level client for
+        * @return The high-level client for a node, or <code>null</code> if the
+        *         node was disconnected or removed
+        */
+       public HighLevelClient borrowHighLevelClient(Node node) {
+               synchronized (syncObject) {
+                       if (!nodeClients.containsKey(node)) {
+                               return null;
+                       }
+                       HighLevelClient highLevelClient = nodeClients.get(node);
+                       while (nodeClients.containsKey(node) && usedConnections.contains(highLevelClient)) {
+                               try {
+                                       syncObject.wait();
+                               } catch (InterruptedException ie1) {
+                                       /* ignore. TODO - check. */
+                               }
+                       }
+                       if (!nodeClients.containsKey(node)) {
+                               return null;
+                       }
+                       usedConnections.add(highLevelClient);
+                       return highLevelClient;
+               }
+       }
+
+       /**
+        * Returns a borrowed high-level client.
+        * 
+        * @see #borrowHighLevelClient(Node)
+        * @param highLevelClient
+        *            The high-level client to return
+        */
+       public void returnHighLevelClient(HighLevelClient highLevelClient) {
+               synchronized (syncObject) {
+                       if (!clientNodes.containsKey(highLevelClient)) {
+                               return;
+                       }
+                       usedConnections.remove(highLevelClient);
+                       syncObject.notifyAll();
+               }
+       }
+
        //
        // PRIVATE METHODS
        //