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.

Similar Messages

  • Priority-queue out and 3750

    Does 3750 switch still need command "priority-queue out"? I noticed when I apply " auto qos voip cisco-phone", it doesn't auto generate "priority-queue out" any more. I know this command is useful in 3550 to prioritize the voice traffic.

    This release contains these new switch features or enhancements:
    Quality of service (QoS) egress priority queue on a port. Shaped round robin (SRR) services the priority queue until it is empty before servicing the other three queues. You enable the egress priority queue by using the priority-queue out interface configuration command.
    QoS Differentiated Services Code Point (DSCP) transparency allows the user to prevent the switch from rewriting the DSCP field in the user IP packet when QoS is enabled.
    http://www.cisco.com/univercd/cc/td/doc/product/lan/cat3750m/12114ax/ol464603.htm

  • 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 :)

  • Advantages of Using Queued Message Handler vs. Standard State Machine

    Hello,
    What are the advantages of using a Queued Message Handler?  Also, why are they more powerful than using Standard State Machines?
    Thanks!

    They are really just sort of an extension of a state machine.  The general idea is that you have one loop doing a specific job.  You then use a queue to tell it how/when to do this job.  For instance, I might have a log file loop.  I will send it commands to open a file, write some data, write some more data, and finally close the file.  Each of those commands are coming from the queue.  The beauty with this setup is that anybody that can get a reference to that queue can send the command to that loop.
    So the QMH is "better" than a state machine mostly because of the decoupling of functions.  In a given application, I will have a loop for log file writing, GUI updates, reading of a DAQ, instrumenet communications, server communications, etc.  Trying to do all of that in a single loop state machine is a major pain in the rear end.  Seperating them out makes life so much easier.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • 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.

  • Custom  order of priority queue

    I am a novice in Java. I intend to use a priority queue which holds objects. The objects have a string and two integers. I have to order the priority queue based on one of the integer.
    I write syntax according to my understanding please correct me.
    PriorityQueue<Object> pr = new PriorityQueue<Object>();
    comparable(){
    sort(Object.int2)// this is the place where I am confused
    }

    Here's an example:
    public class Caller
        public static void main(String[] args)
            Flight f1 = new Flight( "java", 2, 34 );
            Flight f2 = new Flight( "java", 2, 3 );
            Flight f3 = new Flight( "java", 2, 4 );
            Flight f4 = new Flight( "java", 2, 64 );
            Flight f5 = new Flight( "java", 2, 22 );
            Flight f6 = new Flight( "java", 2, 12 );
            PriorityQueue pq = new PriorityQueue();
            pq.add(f1);
            pq.add(f2);
            pq.add(f3);
            pq.add(f4);
            pq.add(f5);
            pq.add(f6);
            System.out.println(pq.poll());
            System.out.println(pq.poll());
            System.out.println(pq.poll());
            System.out.println(pq.poll());
            System.out.println(pq.poll());
            System.out.println(pq.poll());
    public class Flight implements Comparable
        private String airlinename;
        private int flightnumber;
        private int number;
        public int compareTo(Object o)
            Flight f = (Flight) o;
            return number - f.getNumber();
        public String toString()
            return airlinename + " - " + number;
        public Flight(String airname, int num1, int num2)
            airlinename = airname;
            flightnumber = num1;
            number = num2;
        public String getAirlinename()
            return airlinename;
        public void setAirlinename(String airlinename)
            this.airlinename = airlinename;
        public int getFlightnumber()
            return flightnumber;
        public void setFlightnumber(int flightnumber)
            this.flightnumber = flightnumber;
        public int getNumber()
            return number;
        public void setNumber(int number)
            this.number = number;
    }Got it?

  • 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.

  • 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.

  • 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

  • Implemeting a priority queue

    Hi all,
    i have written a priority queue which implements a priority queue interface however i'm getting a liitle stuck. I'm pretty new to Java programming, i'm trying to write a hosptial simulation where ill people arrive and are given a priority to be seen by a medic.
    Every patient that is added to the queue has an int prioriy and the patient that is serviced next is the one with the highest priority. There are three priorities, low, medium, high. If more than one patient has the same highest priority, the patient with that priority that has been longest in the queue will be serviced.
    Could you please help me out to see where my mistakes are?
    Thanks
    The priority queue interface
    import java.util.Iterator;
    public interface PriorityQueue
    * Adds element to the priority queue
    * @param element - the element to be added to the queue.
    public void add (Priority element);
    * Removes the next element from the priority queue
    * Precondition: size() != 0
    public void remove ();
    * The next element to be serviced. This is the element in the queue that has
    * the highest priority. If more than one element has the highest priority,
    * the one which was added to the queue earliest is returned.
    * Note that this has no effect on the queue - you must call remove as well to
    * change the queue state.
    * Precondition: size() != 0
    * @return the next element to be serviced.
    public Priority next();
    * @return the number of elements in the priority queue
    public int size();
    * @return an Iterator for the priority queue.
    public Iterator iterator
    The priority queue
    import java.util.ArrayList;
    import java.util.Iterator;
    public class PriorityQueueImpl implements PriorityQueue
    private final static int DEFAULT_PRIORITY_COUNT = 3;
    private ArrayList elements = new ArrayList();
    public void add (Priority element)
    elements.add (element);
    public void remove ()
    Iterator it = elements.iterator();
    it.remove();
    public Priority next()
    Iterator it = elements.iterator();
    Priority p, highestPriority;
    while (it.hasNext())
    p = it.next();
    if (p.priority > highestPriority.priority)
    highestPriority = p;
    else if (p.priority == highestPriority.priority &&
    p.admissionTime < highestPriority.admissionTime)
    highestPriority = p;
    public Iterator iterator()
    Iterator it = new Iterator()
    int size = size();
    int priority = priority;
    return it;
    public int size()
    int size = 0;
    if (queue[i] !=null)
    size += queue.size();
    return size;

    Hi there,
    I guess you are on the Herts uni course like myself, right? Have you had any luck with getting this to work, or are you still stuck like me?!
    cheers
    Matt Brett

  • Question: Priority Queue "deleteMin()" trouble

    Hello, I am having trouble formulating a delete() method here, which could also be called deleteMin() here.
    The priority queue, is suppose to have quick insertion O(1) time, and slow deletion O(N) because it's going to have to search through the unordered array, find the minimum object then delete it once "delete()" is called.
    However, I am stuck on trying to come up with the logic for my delete() method....
    Here's what I am thinking...
    I need to examine all the items and shift half of them, on average, down to fill in the hole once the minimum item is found.
    How would I find the minimum item, and once found how would I delete this? Any direction or statements you can show me to clear this up would be appreciated. Please see my code below :) Please excuse my empty javadocs as of right now, I do those last.
    Thank you
    * This class is to demonstrate.....
    * @version 1.0
    public class PriorityQ {
         private int maxSize;
         private long[] queArray;
         private int nItems;
          * Javadoc here
         public PriorityQ(int s) // constructor
              maxSize = s;
              queArray = new long[maxSize];
              nItems = 0;
          * Javadoc here
         public void insert(long value) {
              queArray[nItems] = value;
              nItems++;
          * Javadoc here
          public long remove () {
          * Javadoc here
         public long peekMin() {
                   return queArray[nItems - 1];
          * Javadoc here
         public boolean isEmpty() {
                   return (nItems == 0);
          * Javadoc here
         public boolean isFull() {
                   return (nItems == maxSize);
    } // end class PriorityQ
    class PriorityQApp {
                 public static void main(String[] args)
                    PriorityQ q1 = new PriorityQ(5);
                    q1.insert(30);
                    q1.insert(50);
                    q1.insert(10);
                    q1.insert(40);
                    while( !q1.isEmpty() )
                       long item = q1.remove();
                       System.out.print(item + " ");  // 10, 20, 30, 40, 50
                       }  // end while
                    System.out.println("");
         } // end main()
    } // end class PriorityQApp
    // //////////////////////////////////////////////////////////////Edited by: Cole1988 on Feb 21, 2009 9:03 AM

    Sorry no one got to you sooner.
    Using your instance variables:
    public long remove()
         long minValue = Long.MAX_VALUE;
         int minIndex = 0;
         for(int i = 0; i < nItems; i++) //Here we iterate through all the items to find the smallest one
              if(queArray[i] < minValue) //If this particular value is less than the smallest one found so far,
                   minValue = queArray; //This value is now the smallest one found so far
                   minIndex = i; //minIndex now contains the index of the smallest one found so far
         /*Now we can remove the smallest term, because after the above iteration, minIndex is the index number of the smallest value and minValue is the smallest value.*/
         for(int i = minIndex + 1; i < nItems; i++) //Starting at the term right AFTER the smallest one
              queArray[i-1]=queArray[i]; //Copy the value into the space right BEFORE it
         nItems--; //The number of items has decreased by one
         return minValue;
    }Note: This code does NOT resize your array after you remove an item; depending on how you'll implement it, you'll need to check if you're about to overflow the array by comparing nItems with queArray.length and resize your array accordingly.
    It seems like you're a bit confused about loops and iterating through arrays; I'd recommend reviewing a good Java book or online tutorial and practicing with some basic array iterations before you go any farther. You've got the basic grasp of things, it just hasn't "clicked" for you yet. :)
    Let me know if you need any more help or if you don't understand anything about what I just said.
    Regards,
    Alvin                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Priority Queue Question

    If compareTo returns negative, does that mean that the object it was invoked on is higher or lower priority?
    Also in a priority queue, is it invoked on the inserted object or on the object already in the queue?

    If compareTo returns negative, does that mean that
    the object it was invoked on is higher or lower
    priority? If a.compareTo(b) returns a negative value, that means a is "less than" be by whatever sematics apply for the objects in question.
    Whether it means "higher" or "lower" priority depends on how that class is implemented. If you're implementing it, you can use it whichever way you want. Just make sure it's at least somewhat logical and that you document your decision.
    If it's a third-party or core API class, then look at the API docs and/or source code, or just write a little test program to find out how that particular class interprets negative/positive vis-a-vis "higher"/'lower" priority.
    Also in a priority queue, is it invoked on the
    inserted object or on the object already in the queue?????

  • 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.

  • Priority Queue using Vector

    I am trying to develop Priority Queue using vector. For inserting elements I need to check if the inserted objects have greater key I want to shift them. In short, I want to store objects in vector in sorted manner (sort by key). I need help for that.
    The code I have created so far is like this:
    import PriorityQueue;
    import java.util.*;
    import java.io.*;
    public class PQItem
         private Object e;
         private int k;
         public PQItem(int key, Object element)
              k=key;
              e=element;
         public int key(){ return k;}
         public Object elelment(){ return e;}
         public void setkey(int key){k=key;}
         public void setElement(Object element){e=element;}
         public static void main(String args[])
              FileReader fr;
              fr = openfile();
         public static FileReader openfile()
              String line,name,file="test.txt";
              int vsize,k1,i1=0;
              boolean flag;
              Object e1,e2;
              //Vector v = new Vector();
              PriorityQueue q=new PriorityQueue();
              try
                   FileReader fr=new FileReader(file);
                   BufferedReader inFile = new BufferedReader(fr);
                   String del=",";
                   line=inFile.readLine();
                   StringTokenizer tokenizer=new StringTokenizer(line,del);
                   while(line!=null)
                        tokenizer = new StringTokenizer(line,del);
                        k1 = Integer.parseInt(tokenizer.nextToken());
                        e1 = tokenizer.nextToken();
                        //System.out.println(line);
                        q.InsertItem(line,i1);
                        line=inFile.readLine();
                        i1++;
                   flag=q.isEmpty();
                   System.out.println(flag);
                   vsize=q.size();
                   System.out.println(+vsize);
                   e2=q.last();
                   System.out.println(e2);
              }//try
              catch(FileNotFoundException exception)
                   System.out.println("The File "+file+" was not found");
              catch(IOException exception)
                   System.out.println(exception);
              return null;
         }//filereader
    //The other file is
    import java.util.*;
    public class PriorityQueue
         private Object[] a;
         Vector v = new Vector();
         //Constructor
         public PriorityQueue()
         public int size() {return v.size();}
         public boolean isEmpty() { return (v.size())==0;}
         public void InsertItem(Object e,int k)
              v.insertElementAt(e,k);
              //new code
              //for(int i=0;i<size;i++)
         public Object last()
              return v.lastElement();

    Why not let Java do the work - use a java.util.TreeSet instead of a Vector.
    Make your PQItem implement Comparable, write a compareTo(Object o) method (and an equals method for completeness) and you're golden. Then when you add(pqItem) it goes in the exact spot it belongs.

  • Priority Queue add help?

    ok, I'm making a priority queue from a List and I'm trying to figure out how to add to the queue so that the items are stored in the queue in order and this is what I have.
    On the line that starts if(newItem.compareTo... eclipse is giving me a warning:
    Type safety: The method compareTo(Object) belongs to the raw type Comparable. References to generic type Comparable<T> should be parameterized
    And I dont know what that means? will my add method work as planned?
    Also, my List class has a max size (that is private) and I want it so that if the priority queue tries to add over the max size it will throw an exception but the commented out line just causes an error...any ideas?
    Thanks
         public void enqueue(Comparable newItem) throws QueueException
              //if(aList.size() == MAXLIST) throws Exception
              if(aList.size() == 0) aList.add(1, newItem);
              else
                   for(int i = 1; i <= aList.size(); i++)
                        if(newItem.compareTo(aList.get(i)) == -1) aList.add(i, newItem);
         }

    And I dont know what that means? The warning is referring to generics: http://java.sun.com/docs/books/tutorial/extra/generics/index.html

Maybe you are looking for