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.

Similar Messages

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

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

  • Is message persistance with 3rd party queues implemented?

    Is message persistance with 3rd party queues implemented for 9.0.2 or 9.0.3 prev?
    I am not able to use Oracle JMS and want to try implementing this.
    Documents on how to implement this would be helpful.
    thanks,
    Isaac

    OC4J 9.0.2 is certified with few JMS providers like MQSeries, SonicMQ, SwiftMQ, etc. Please look at the Services Guide that documents how to use 3rd Party JMS providers.
    regards
    Debu

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

  • 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

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

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

  • How to run tasks with priority?

    Hello everyone,
    I want to run tasks with priority, i.e. among several simultaneous running tasks, the task with the higher priority will have more chances to occupy CPU time. I have the following 2 issues dealing with the implementation of such feature.
    - To define each task as a thread or as a method? How to change the priority of each task dynamically when they are running?
    - The priority feature of Java thread does not meet my requirement, since I can not define priority precisely. For example, I want to define that a task with priority A will occupy CPU time 3 times than a task with priority B.
    I am wondering whether I can find similar open source projects or tutorials?
    Thanks in advance,
    George

    how to run autoconfig with out effecting database
    or
    which mode i have to run What do you mean by not affecting the database?
    The database and the database listener should be up and running when you run AutoConfig on the Application/Database tier nodes.
    Please see (Autoconfig FAQ [ID 218089.1]) -- Which files / profile options get changed when I run AutoConfig?
    Thanks,
    Hussein

  • Thread safe Queue implementation

    Dear all,
    I have implemented Queue functionality using Blocking concurent linked list based java queue, but i am facing problem of deadlock/program hang.
    There are 10 threads which are trying to see that is there any object in Queue, they get that object and process it.
    Any idea what is wrong ??
    Thanks
    public class MyQueue
        private LinkedBlockingQueue<Object>  elements;
        private Object obj;
        public MyQueue() {
            elements = new LinkedBlockingQueue<Object>();
            obj=null;
        public Object pull() {
             try {
                   obj = elements.take();
              } catch (InterruptedException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              return obj;
        public void push(Object o) {
             try {
                   elements.put(o);
              } catch (InterruptedException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
        public Object[] removeAllObjects() {
            Object[] x = elements.toArray();
            elements.clear();
            return x;
    }

    Thanks,
    I analyzed the hanged/deadlocked program by killing its process with command "kil -3 <pid>"
    i have seen following state for my JobHandler threads
    is any wrong with Queue implementation or some thing else , Any idea?
    "JobHandler" prio=10 tid=0xaec22000 nid=0x51c7 waiting on condition [0xaeb0b000..0xaeb0c030]
       java.lang.Thread.State: WAITING (parking)
            at sun.misc.Unsafe.park(Native Method)
            - parking to wait for  <0xee01fa00> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
            at java.util.concurrent.locks.LockSupport.park(LockSupport.java:158)
            at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:1925)
            at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:358)
            at MyQueue.pull(MyQueue.java:89)
            at JobHandler.run(JobHandler.java:264)

Maybe you are looking for

  • Huge iMovie file

    I've made many iMovies and iDVDs using iMovie6. I'm putting them on a LaCie 1TB external hard drive. The current movie that I'm making by cutting and pasting two movies together is about 2 hrs long and the file size is about 500GB! It hs 95 clips, th

  • Device for sound output changing randomly

    After the latest OS update, I've been having issues with my sound output settings. My sound will play most the time through the "line out" setting, but then randomly the "sound effects" will play thru the internal speakers. I keep changing the settin

  • ?? How do I change the info i put in during set up?

    I will be selling my macbook to someone--how do i change the info i put in during set up (such as address, name, phone number, etc.)?? I feel a lot safer to sell the macbook without those info in the computer.

  • Virtualbox: Compositing does not work, compiz crashes

    So, here's my problem: After installing a fresh Arch Linux, the first thing I did was install Xorg and Virtualbox guest modules. After doing all that, and running Xfce, it worked just fine... except there was no compositing. When I installed Compiz a

  • How to tell whether a license used to install SQL Server is MSDN license or Volume license?

    I want to check license used to install SQL Server is MSDN license or Volume license for SQL Servers which are at least SQL Server 2008 on Windows 2008 R2.  Is there any script/command/tool that I can run on Windows or SQL Server to find such informa