Servlet with a priority queue (heap)

Hi,
The following is a snipet of code in my applet. It sends a request to a servlet. The request contains a parameter "priority":
String inline = "GET //http/hostanme/servlet/FancyServlet?entry=4&priority=6"
URL url = new URL(inline);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = in.readLine();
The skeleton of my server is listed below. It inserts the request in a heap, and then retrieves the request with the lowest priority from the heap. This request (not necessarily the one that came in) is processed. My question is, how do I send the response to the correct client?
Thanks for your help,
Miguel
public class RequestSchedulerServlet extends HttpServlet {
static Heap heap = new Heap();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String entry = request.getParameter("entry");
String priority = request.getParameter("priority");
heap.insert(new Request(entry,priority));
Request req = heap.findMin();
String out = processReq(req);
// here is where I want to send out to the correct client

Well, this might be a swifty thing to do, unfortunately the Java Dudes in their infinite wisdom decided that asynchronous servlets were a bad thing. I disagree mind you. So while you could do what you wanted, you still have all these threads hangin' out waiting for their work to be done, which is just really lamo.
Anyhoo, to do this, just add a reference to the socket in the entry class, and when you pick up an entry from the heap, you can fetch the socket again, and send the results back to that socket. Of course you're probably going to moof up session info, and timeouts et. cetera, but it might work.

Similar Messages

  • Priority queues for external loading

    Hi, I was wondering if there was a way to load multiple external files (via the Loader class) in parrallel, but with a priority queue. That is, I want to load 5 images, but I want image 1 loaded as fast as possible.
    Obviously I could make my own load queue, but if I do that the loading process could easily get hung up on loading a single image.
    I want to be able to run multiple Loader.load()s in parrallel, but assign priority weighting to each of the files.

    i don't know of any way to pause a loading file with flash.   in as3 once a file starts to load you can either let it complete loading or you can stop its load.  if you stop its load and then later want to continue, you must restart from the begining.  i don't believe flash has any way to complete the load of a partially downloaded file.

  • D-ary heap with Priority Queue implementation

    I have to construct a program that find the k-th smallest integer in a given set S of numbers; read from the standard input a first line containing positive integers N, k, and d separated by spaces. Each of the following N lines contains a positive integer of the set S. I have to implement a generic d-ary heap class that implements all methods of the priority queue interface.
    i have the following code...but the inserting bubbling doesnt seem to wokr right...
    any help would be great:
    import java.util.*;   
    public class Heap {
        static Element[] heap;
        int N;
        static int k;
        int d;
        static int size = 0;
        Compare comp;
        public Heap(int nodes, int max, Compare c)
            N = max;
            d = nodes;
            heap = new Element[N];
            comp = c;
        public static void main(String args[])
            Scanner _scan = new Scanner(System.in);
      //      String Nkd = _scan.nextLine();
       //     Scanner _scanNkd = new Scanner(Nkd);
            int _N = 0;
            int _d = 0;
            Compare _c = new Compare();
                _N = _scan.nextInt();
                k = _scan.nextInt();
                _d = _scan.nextInt();
            Heap _heap = new Heap(_d,_N,_c);
            int i=0;
            int num=0;
            while(_scan.hasNextLine()&&num<_N)
                System.out.println("test" + _scan.nextInt());
                _heap.insert(i, _scan.nextInt());
                i++;
                size++;
                num++;
            for(int z=0;z<_N;z++)
            //    System.out.println(heap[z].getKey());
            Element kth = null;
            for(int j = 1; j <=k; j++)
                kth = _heap.removeMin();
            System.out.print(kth.getKey());
            System.out.print('\n');
            /*System.out.print(k);
            System.out.print('\n');
            System.out.print(_heap.size());
            System.out.print('\n');
            System.out.print('\n');
            System.out.print(heap[0].getKey());
            System.out.print('\n');
            System.out.print(heap[1].getKey());
            System.out.print('\n');
            System.out.print(heap[2].getKey());
            System.out.print('\n');
            System.out.print(heap[3].getKey());
            System.out.print('\n');
            System.out.print(heap[4].getKey());
            System.out.print('\n');
            System.out.print(heap[5].getKey());*/
        public void insert(int i, int e)
            heap[i] = new Element(e,i);
            this.bubbleUp(heap);
    public int size() {return size;}
    public boolean isEmpty() {return(size == 0);}
    public int min(){return heap[0].getKey();}
    public Element remove()
    int i = size-1;
    size--;
    return heap[i];
    public Element removeMin()
    Element min = this.root();
    if(size == 1)
    this.remove();
    else
    this.replace(this.root(), this.remove());
    this.bubbleDown(this.root());
    return min;
    public Element replace(Element a, Element b)
    a.setIndex(b.getIndex());
    a.setKey(b.getKey());
    return a;
    public void bubbleUp(Element e)
    Element f;
    while(!e.isRoot(e.getIndex()))
    f = this.getParent(e.getIndex());
    if(comp.compare(f,e) <= 0)
    break;
    else
    int temp = f.getIndex();
    f.setIndex(e.getIndex());
    e.setIndex(temp);
    swap(f,e);
    System.out.println("bubbling");
    e=f;
    public void bubbleDown(Element e)
    int i = e.getIndex();
    while(e.isInternal(i, size))
    Element s;
    if(!e.hasRight(i, size))
    s = this.getLeft(i);
    else if(comp.compare(this.getLeft(i), this.getRight(i)) <= 0)
    s = this.getLeft(i);
    else
    s = this.getRight(i);
    if(comp.compare(s,e) < 0)
    swap(e,s);
    e = s;
    else
    break;
    public void swap(Element x, Element y)
    int temp = x.getIndex();
    x.setIndex(y.getIndex());
    y.setIndex(temp);
    public Element root() {return heap[0];}
    public Element getLeft(int i) {return heap[i*2];}
    public Element getRight(int i) {return heap[i*2+1];}
    public Element getParent(int i) {return heap[i/2];}
    class Element
    private int key;
    private int index;
    public Element(int k, int i)
    key = k;
    index = i;
    public int getKey() {return key;}
    public void setKey(int k) {key = k;}
    public int getIndex() {return index;}
    public void setIndex(int i) {index = i;}
    public boolean isRoot(int i) {
    if (i == 0)
    return true;
    else
    return false;
    //return i == 1;
    public boolean hasLeft(int i, int size) {return 2*i <= size;}
    public boolean hasRight(int i, int size) {return 2*i+1 <= size;}
    public boolean isInternal(int i, int size) {return hasLeft(i, size);}
    public boolean isExternal(int i, int size) {return !isInternal(i, size);}
    class Compare implements Comparator<Element>
    public Compare(){}
    public int compare(Element a, Element b)
    int x=0;
    if(a.getKey() < b.getKey())
    x = -1;
    else if(a.getKey() == b.getKey())
    x = 0;
    else if(a.getKey() > b.getKey())
    x = 1;
    return x;

    Well, this might be a swifty thing to do, unfortunately the Java Dudes in their infinite wisdom decided that asynchronous servlets were a bad thing. I disagree mind you. So while you could do what you wanted, you still have all these threads hangin' out waiting for their work to be done, which is just really lamo.
    Anyhoo, to do this, just add a reference to the socket in the entry class, and when you pick up an entry from the heap, you can fetch the socket again, and send the results back to that socket. Of course you're probably going to moof up session info, and timeouts et. cetera, but it might work.

  • [svn] 3497: Changing internal datastructure utilized by the LayoutManager' s priority queue, in order to provide a mechanism for quicker lookup of items being validated with 'ValidateNow/ValidateClient'.

    Revision: 3497
    Author: [email protected]
    Date: 2008-10-06 14:48:38 -0700 (Mon, 06 Oct 2008)
    Log Message:
    Changing internal datastructure utilized by the LayoutManager's priority queue, in order to provide a mechanism for quicker lookup of items being validated with 'ValidateNow/ValidateClient'. Will be keeping a close watch on perf suite results after this change, to ensure we did not inject memory issues.
    Reviewer: Glenn
    QA: No (Keeping watch on Mustella, but cyclone looked good).
    Modified Paths:
    flex/sdk/trunk/frameworks/projects/framework/src/mx/managers/layoutClasses/PriorityQueue. as

  • Java priority queue

    Java provides PriorityQueue, and I have gone through its API.
    The implementation of PriorityQueue in Java does not provide method for increase or decrease key,
    and there must be a reason for it.
    But, when i go through books on data strucutre, a lot of them talk about the increase/decrease key function
    of the PriorityQueue.
    So I am just wondering, why is it that increase/decrease function not provided in PriorityQueue. I cannot come up with a reason for it, but i think there must be. Does anybody have any thought on this. Or is it just
    because the designers thought its not needed?
    I checked the source for the Priority Queue and the heapify() method was declared private.

    lupansansei wrote:
    I have used Java's priority queue an I have written my own but I have never come accros the terms "increase or decrease key". Do you mean something like 'upheap' or 'downheap' in relation to a 'heap' implementation meaning move an entry to it correct position if the key changes? If so then one should make the 'key' immutable so that the functions are not needed.
    Yes, i mean 'upheap' or 'downheap' by increase or decrease key. Sorry
    maybe my choice of words was not correct.
    I couldn't get what you mean by 'key' immutable. Can you please explain it. If the key cannot change (i.e. it is immutable) then there is no need to ever change the position of an element.
    >
    Correct. Since the PriorityQueue does not need to implemented using a 'heap' there is no need for the heapify() method to be exposed. If one implemented using a balanced tree or a skip list the heapify() method would not be applicable.I am using PriorityQueue and i need to update the priority of the elements and i was wondering whether to implement the whole queue
    myself or look for a better way of using the PriorityQueue class.
    Do you have any suggestions for efficiently updating the priority of element?I have a priority queue implementation where elements know they are in a heap and know where they are in the heap. By doing this I can modify 'keys' and then move a value to it's correct place in the queue in a very short time. The limitations this feature imposes on the elements and the possibility of corrupting the heap means I don't often use this these days. It is far too error prone.
    These days in my simulations I normally remove an element from the queue, process the element and then create new elements and insert them back in the queue. This sometimes takes 2 lots of Log(n) operations where my specialized priority queue just takes Log(n) operations. The code is just so much more maintainable and I accept the hit.

  • Wanted: Flexible Priority Queue

    Given this class
    class Foo {
    private int STATE, VAL;
    // STATEs are unique, VALs are not
    I want a collection C of Foo objects that supports these operations
    in at most O(log n) time.
    (1) boolean C.contains(Object o);
    --> Using STATE as the comparator
    (2) Object C.get(Object o);
    --> Return a reference to the collection object that equals o,
    again, using STATE as the comparator
    (3) Object C.minExtract();
    --> Remove and return the object with the minimum VAL.
    If there is a tie, choose arbitrarily.
    Operations (1) and (2) call for something like a TreeMap.
    But operation (3) wants to treat the collection as a priority queue,
    which is often implemented as a heap data structure -- which I don't
    see in the classes that come with java.
    In fact all the SortedSet and SortedMap collections seem to require
    unique keys, whereas operation (3) wants to keep the collection sorted
    by non-unique VALs.
    Question: are there off-the-shelf classes I can use to efficiently do what
    I want, or do I need to design it from scratch?
    thanks,
    roy

    DragonMan,
    I agree I may have to create a class which manages two data structures. The first, perhaps, a HashSet. but:
    The other a sorted List of some kind, ordered by VAL.The problem here is "what kind"? As I noted, all of java's sorted collections seem to require unique keys, but VAL is not unique. I suppose I could create my own red-balck tree or heap or whatever, but I'd like to see how much mileage I can get out of java first.
    Currently, I'm considering combining STATE and VAL to make a unique key (since STATE already is unique) whose order however, is dominated by the VAL component.
    roy

  • Adaptable Priority Queue ?

    I'm working on a program where I am creating an adaptable priority queue with heaps and I implement the heaps with linked binary trees. Know of any good examples or links on the subject? I know fundamentally what do do, but the syntax is the issue. Thanks for any help.......

    http://java.sun.com/j2se/1.5.0/docs/api/java/util/PriorityQueue.html

  • Priority Queue Ordering

    In the process of using a Priority Queue the question came up about what order elements with equal priority are removed. The two logical orders would be first in, first out, like the standard queue, or first in, last out, like a stack. However, testing the Priority Queue showed that the elements of equal priority were removed in neither order, and moreover, the elements were stored in a neither consistent nor prioritized order. My question is, what causes this situation, is there any way to predict the order in which equally prioritized elements will be removed, and is there any way to force the Priority Queue into removing elements in a first in, first out order without writing my own?

    In the process of using a Priority Queue the question came up ...I don' t know why.The Javadoc clearly specifies that 'ties are broken arbitrarily'.
    My question is, what causes this situationThe fact that it uses a priority heap algorithm, which is where its O(log(n)) performance comes from.
    is there any way to predict the order in which equally prioritized elements will be removedNo.
    and is there any way to force the Priority Queue into removing elements in a first in, first out order without writing my own?Encode insertion time as a minor key of the priority.

  • Does the priority queue always work?

    Hi 
    I have a 8Mbp of wan link which sometime gets saturated and I have shaped average this to 8Mbps but i am running vocie on this WAN link and have defined priority for voice with 850kbps under voice class. My question is when the link is not fully utilized, Will the packets from priority queue are always dequeued first as compared to packets sent from from other queus or will the QoS will not do anything here since the link utilization is lot less than what is sepecified in shape average. I am asking this to confirm if the priority queue always help to overcome the issue of jitter if either the link is saturated or not?
    Thanks

    Disclaimer
    The Author of this posting offers the information contained within this posting without consideration and with the reader's understanding that there's no implied or expressed suitability or fitness for any purpose. Information provided is for informational purposes only and should not be construed as rendering professional advice of any kind. Usage of this posting's information is solely at reader's own risk.
    Liability Disclaimer
    In no event shall Author be liable for any damages whatsoever (including, without limitation, damages for loss of use, data or profit) arising out of the use or inability to use the posting's information even if Author has been advised of the possibility of such damage.
    Posting
    You describe PQ and shaping, but the former is usually a part of doing QoS on L2/L3 switches, and the latter on routers.  What device(s) and their IOS versions and the WAN media are you working with?
    On "routers", interfaces generally have FIFO tx-rings, only when they overflow, are packets placed in CBWFQ queues.  Within CBWFQ, LLQ will be dequeued first, but such packets might have already been queued behind other non-LLQ traffic within the interface tx-ring.  (NB: for routers, with tx-rings, when supporting VoIP, you may want to minimize the size of the tx-ring.)
    Shapers, in my experience, are "interesting".  First, I believe many shapers don't account for L2 overhead, but provider CIRs often do.  So unless you shape slower than the nomimal CIR rate, you can send faster than the available bandwidth.  (Often I've found shaping 10 to 15% slower allows for average L2 overhead.)
    Second, shapers work on averages over time intervals.  For VoIP, you'll often want to insure the shaper is using a small Tc, otherwise it will allow FIFO bursts.  (I've found a Tc of 10ms seems to support VoIP fairly well.)
    Third, I suspect some shapers might have their own queues between the interface and the defined policy queues.  If they do, unknown what their queuing organization is or their supported queuing depths.  If this is the case, makes it difficult to engineer QoS.
    Whenever possible, I've found it beneficial to work to avoid using shapers especially for timing sensitive traffic, like VoIP.  In your case, I would suggest, if possible, obtaining 10 Mbps of WAN bandwidth and somewhere passing the traffic through a physical 10 Mbps interface, with a QoS policy.
    But to more directly answer your question, PQ (or LQ) will dequeue its packets next compared to other "peer" queues.  This should always help VoIP for delay and jitter, but there's more involved whether this is necessary and/or whether it's helpful enough when necessary.
    You ask about when a link is saturated, but a link is 100% saturated everytime a packet is being transmitted.  Often link usage is represented in percentages of usage of possible maximum transmission rate over some time period, but when it comes to QoS, 100% utilization might be just fine while 1% utilization is not.  Much, much more information, about your situation, might be needed to offer truly constructive recommendations.

  • Priority Queues

    hi iam a beginner in java, could you please help me with this code. thanks
    Implement (provide complete Java code) a priority queue using a singly linked list. You may call this class LinkedPriorityQueue. The use of classes contained in the Java Collections framework in the above implementing is strictly forbidden.
    You may need to write a second class, PQNode, which defines the nodes in your linked list. Feel free to implement the PQNode class in anyway that you see fit. However, the LinkedPriorityQueue class should implement all methods and constructors

    Here is the search of the forums
    http://search.java.sun.com/search/java/index.jsp?qp=&nh=10&qt=%22singly+linked+list%22&col=javaforums&x=23&y=16
    Here is a google search
    http://www.google.com/search?hl=en&lr=&ie=ISO-8859-1&q=%22singly+linked+list%22+java
    Due tomorrow???

  • Priority Queue problem

    Hi Everybody.
    Can anyone tell me in which order elements of priority queue are sorted.
    I have used following code
    class Test{
    PriorityQueue <strings> pq=new PriorityQueue <Strings>();
    pq.add("silpa");
    pq.add("swati");
    pq.add("roopa");
    pq.add("abc");
    System.out.println(pq);
    System.out.println(pq.poll());
    System.out.println(pq.peak());
    The output I got is
    [abc silpa swathi roopa]
    abc
    roopa.
    Can anybody explain why the collection elements are not sorted ?
    I am getting correct output with peek() n poll().According that methods i should get
    [abc roopa silpa swathi ]
    Explain the reason?

    System.out.println(pq);This line prints out the contents of the queue, by implicitly calling pq.toString(), whose behaviour is inherited from AbstractCollection, which therefore has nothing to do with sorting. So you have no valid reason for expecting any particular ordering.

  • [svn] 3539: Updated RadioButtonGroup to account for recent changes to LayoutManager priority queue .

    Revision: 3539
    Author: [email protected]
    Date: 2008-10-09 10:58:31 -0700 (Thu, 09 Oct 2008)
    Log Message:
    Updated RadioButtonGroup to account for recent changes to LayoutManager priority queue. The order that a RadioButtonGroup was traversed was always dependent on what order that the radio buttons properties were validated. Since this assumption no longer holds true, we are now very specific about how the group orders the RadioButtons (breadth-first for consistency with Flex 2 and Flex 3).
    Check-in Tests: Pass
    Mustella Tests: (RadioButton, RadioButtonGroup) Pass
    Reviewer: Glenn
    QA: Yes
    Bugs: SDK-17248
    Ticket Links:
    http://bugs.adobe.com/jira/browse/SDK-17248
    Modified Paths:
    flex/sdk/trunk/frameworks/projects/framework/src/mx/controls/RadioButtonGroup.as

    Revision: 3539
    Author: [email protected]
    Date: 2008-10-09 10:58:31 -0700 (Thu, 09 Oct 2008)
    Log Message:
    Updated RadioButtonGroup to account for recent changes to LayoutManager priority queue. The order that a RadioButtonGroup was traversed was always dependent on what order that the radio buttons properties were validated. Since this assumption no longer holds true, we are now very specific about how the group orders the RadioButtons (breadth-first for consistency with Flex 2 and Flex 3).
    Check-in Tests: Pass
    Mustella Tests: (RadioButton, RadioButtonGroup) Pass
    Reviewer: Glenn
    QA: Yes
    Bugs: SDK-17248
    Ticket Links:
    http://bugs.adobe.com/jira/browse/SDK-17248
    Modified Paths:
    flex/sdk/trunk/frameworks/projects/framework/src/mx/controls/RadioButtonGroup.as

  • Low priority and high priority queue

    Hi
    we have high priority and low priority queue's. Functionality wise i know that time critical messages will be sent through high priority queue's and low priority messages will be sent
    through low priority queues. But like to know what technicality makes this separation of
    low priority and high priority queue's ? The crus of the question is what technical setting(s)
    makes the queue as high priority and what technical setting(s) makes the queue as low priority
    queue.
    Thanks
    kumar

    i Michal
    I am talking abt queue prioritization on Integration eninge only.
    I am good with queue prioritization and am able to successfully implement
    the same. We are using only PI7.0.
    My question is what is the technical difference between high priority
    and low priority queues ? what technical setting makes it a high priority
    queue and what technical setting makes a low priority queue ?
    Your answer:
    how the system reacts to new messages if almost all queues are already blocked
    for some types of messages
    My comment: what setting makes the system to behave like that ? what property
    of that queue makes them to behave like that ?
    Thanks
    kumar

  • Egress queueing - priority-queues and queue-sets

    If I use the priority-queue out command on an interface 3750 does this treat queue1 as the priority queue?
    How can I tell which traffic is sent to each queue by default? Or do I have to specifically define it such as
    mls qos srr-queue output dscp-map queue 1 threshold 3 40 41 42 43 44 45 46 47
    I really want dscp 40-47 to go priority and the rest to be spread evenly across the other 3 queues as the vast majority of the rest of the traffic will be 0. Is there a command that lets the other 3 queues be best effort?
    Also, is this an OK config to use with priority-queueing? I don't actually want a large amount of bandwidth for the priority traffic, just for it to be expidited.
    Queueset: 2
    Queue : 1 2 3 4
    buffers : 10 30 30 30
    threshold1: 100 200 100 100
    threshold2: 100 200 100 100
    reserved : 50 50 50 50
    maximum : 400 400 400 400
    Any help very gratefully received.
    Thanks, J

    Sorry, just bouncing this to see if anyone around today can help :)

  • Priority queue out handling.

    We're testing the reference system shown in the figure below.
    System Description
    Four 2960 switches are used for transport;
    Equipment 1 and Equipment 2 exchange packets for synchronization;
    To reach synchronization  Equipment 1 and 2 must exchange data with a very low jitter.
    2960 Configuration details
    Four our test puprose, we're using 100Mbit/s ports (22 and 23) as trunk.
    In order to obtain minimum jitter We performed these configurations:
    We Enabled QoS;
    We Marked Synchronization packets with CoS 7 and DSCP 63;
    We marked other kind of traffic inserted in different ports) with CoS 0;
    We set "trust DSCP" on trunk ports;
    On the trunk ports we mapped traffic with CoS 7/DSCP 63 (and only this) on output queue 1;
    We enabled the expedite queue (priority-queue out).
    Question
    With these settings we aim at forcing our synchronization packtes to precede other kind of traffic and go from Equipment 1 to Equipment 2 with minimum jitter.
    Unfortunately we experienced  high jitter when both synchronization packets and other traffic are sent through the systems.
    What is wrong in our assumptions or configurations?
    What is the real behaviour of the expedit queue?

    Seems the right config.
    This is the my configuration and it works well:
    #global level
    mls qos srr-queue input priority-queue 2 bandwidth 20
    mls qos srr-queue input cos-map queue 1 threshold 3  0 1 2 3 4
    mls qos srr-queue input cos-map queue 2 threshold 3  5 6 7
    mls qos srr-queue output cos-map queue 1 threshold 3  5 6 7
    mls qos srr-queue output cos-map queue 2 threshold 3  4
    mls qos srr-queue output cos-map queue 3 threshold 3  2 3
    mls qos srr-queue output cos-map queue 4 threshold 3  0 1
    mls qos
    #port level
    mls qos trust dscp
    priority-queue out
    What is your IOS version?
    Can you use the 2960 Gigabit port?
    Regards.

Maybe you are looking for

  • Can't run Release configuration

    Hi everyone, I can run Debug configuration of my application for Mac OS X, but when I try to run Release configuration Xcode writes "The program being debugged i not being run". I checked project settings several times. The file exists. XCode 6.2.4.

  • How to setup remote access with E4200?

    Hi, I am new to this and I need help from you all on how to setup the E4200 so that I can access the media server when I am in office?  Is there a guide or step by step procedure on this?  I was browsing on the Cisco website and unable to find it. 

  • Transfer order printing-Urgent

    Hi Do anybody know how to print multiple transfer orders in a single go rather than printing TOs one by one using LT31. Thanks

  • Render Related -JSF Third party Component

    Hai All I am having doubt regarding JSF Third party component like Jmaki ,MyFaces or something like that . How the third party component match with JSF life cycle even though there is no java classes for managing and rendering the Third party compone

  • Idvd encoding error during burning

    unable to burn imovie project using Idvd...encoding error