| 1 18 package freecs.core; 19 import freecs.util.ObjectBuffer; 20 import freecs.Server; 21 import java.nio.channels.SelectionKey ; 22 23 public class RequestQueue { 24 private long lastCheck; 25 private float lastPerc = 0; 26 private RequestReader req; 27 28 private ObjectBuffer requests; 29 30 public RequestQueue (RequestReader r) { 31 requests = new ObjectBuffer (Server.srv.READER_MAX_QUEUE); 32 req=r; 33 if (Server.TRACE_CREATE_AND_FINALIZE) 34 Server.log (this, "++++++++++++++++++++++++++++++++++++++++CREATE", Server.MSG_STATE, Server.LVL_VERY_VERBOSE); 35 } 36 37 public double getUsage () { 38 double onePerc = ((double) requests.capacity ()) / ((double) 100); 39 return ((double) requests.size()) / onePerc; 40 } 41 42 public boolean addKey (SelectionKey sk) { 43 if (!CentralSelector.isSkValid(sk)) { 44 Server.log(this, "addKey: tryed to add invalid key", Server.MSG_STATE, Server.LVL_VERBOSE); 45 return true; 46 } 47 int i = 0; 48 synchronized (requests) { 49 while (!requests.put (sk)) { 50 if (i > 5) { 51 Server.log (this, "addKey: Tried 5 times to add key.", Server.MSG_STATE, Server.LVL_MAJOR); 52 requests.notify(); 53 return false; 54 } 55 try { 56 requests.wait (200); 57 } catch (InterruptedException ie) { } 58 i++; 59 } 60 requests.notify(); 61 } 62 return true; 63 } 64 65 public int size () { 66 return requests.size(); 67 } 68 69 public SelectionKey getKey (long timeout) { 70 long returnTime = System.currentTimeMillis () + timeout; 71 SelectionKey sk; 72 synchronized (requests) { 73 sk = (SelectionKey ) requests.get (); 74 while (sk == null && System.currentTimeMillis () < returnTime) { 75 try { 76 long diff = returnTime - System.currentTimeMillis(); 77 if (diff > 0) 78 requests.wait (diff); 79 } catch (InterruptedException ie) { } 80 sk = (SelectionKey ) requests.get (); 81 } 82 requests.notify(); 83 } 84 return sk; 85 } 86 87 public SelectionKey popKey (long timeout) { 88 synchronized (requests) { 89 SelectionKey rk = this.getKey(timeout); 90 if (rk == null) 91 return null; 92 if (!requests.isEmpty()) 93 requests.pop(); 94 requests.notify(); 95 return rk; 96 } 97 } 98 99 public String toString() { return "[RequestQueue]"; } 100 101 public void finalize() { 102 if (Server.TRACE_CREATE_AND_FINALIZE) 103 Server.log(this, "----------------------------------------FINALIZED", Server.MSG_STATE, Server.LVL_VERY_VERBOSE); 104 } 105 } | Popular Tags |