LinkedList Queue Implementation

Hey guys/gals,
Just messing around here with a LinkedList Queue implementation. Look at the code. Theres the main class with the main method. Theres the Node class that holds info for my nodes. Theres the Queue class that sets up the Queue with a linkedlist. In my main method im having problems with accessing the 4th node. Its created and put into the queue(linkedList) but whenever it is processed with the toString() method the LinkedList is giving indexOutofBounds index 1 size 1. Not sure why. Any help is appreciated thank you in advance. Code is below.
import java.util.*;
public class DijAlg {
        static int source = 0;
        static Queue Queue = new Queue();
        static int NUMBEROFNODES = 4;
    public static void main(String args[]){
    Node NodeA = new Node(), NodeB = new Node(), NodeC = new Node(), NodeD = new Node();
    Node[] Nodes = {NodeA, NodeB, NodeC, NodeD};
    for (int i = 0; i< NUMBEROFNODES; i++){
     for (int v = 0; v< NUMBEROFNODES; v++){
         Nodes.dist[v] = 10000;
Nodes[i].previous[v] = 99;
Nodes[i].dist[source] = 0; // Distance from source to source
Queue.enqueue(NodeA);
Queue.enqueue(NodeB);
Queue.enqueue(NodeC);
Queue.enqueue(NodeD);
int i = 0;
while (!Queue.isEmpty()){
System.out.println("Node " + i);
System.out.println(((Node)Queue.peek()).toString());
Queue.dequeue();
i++;
static class Node {
int [] dist;
int [] previous;
Node(){
dist = new int [NUMBEROFNODES];
previous = new int [NUMBEROFNODES];
public String toString(){
String myString = "Dist ";
for(int i = 0; i < NUMBEROFNODES ; i++){
myString = myString.concat(String.valueOf(dist[i]) + ", ");
myString.concat("Prev ");
for(int i = 0; i < NUMBEROFNODES; i++){
myString = myString.concat(String.valueOf(previous[i]) + ", ");
return myString;
class Queue {
     LinkedList list;
     // Queue constructor
     Queue()
          // Create a new LinkedList.
          list = new LinkedList();
     boolean isEmpty()
     // Post: Returns true if the queue is empty. Otherwise, false.
          return (list.size() == 0);
     void enqueue(Object item)
     // Post: An item is added to the back of the queue.
          // Append the item to the end of our linked list.
          list.add(item);
     Object dequeue()
     // Pre: this.isEmpty() == false
     // Post: The item at the front of the queue is returned and
     // deleted from the queue. Returns null if precondition
     // not met.
          // Store a reference to the item at the front of the queue
          // so that it does not get garbage collected when we
          // remove it from the list.
          // Note: list.get(...) returns null if item not found at
          // specified index. See postcondition.
          Object item = list.get(1);
          // Remove the item from the list.
          // My implementation of the linked list is based on the
          // J2SE API reference. In both, elements start at 1,
          // unlike arrays which start at 0.
          list.remove(1);
          // Return the item
          return item;
     Object peek()
     // Pre: this.isEmpty() == false
     // Post: The item at the front of the queue is returned and
     // deleted from the queue. Returns null if precondition
     // not met.
          // This method is very similar to dequeue().
          // See Queue.dequeue() for comments.
          return list.get(1);
Edited by: venture on Dec 17, 2008 4:51 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Thanks for the help Encephalopathic. I came to the same conclusion but it just didn't add up when I looked through the code. The problem was that whoever wrote the code for the queue class(I borrowed the code) had used get(1) instead of getFirst(), and remove(1) instead of removeFirst(). So it was totally skipping the first index A.K.A ----> 0. New code below. Also added a name field that helped me to debug, Node "A" was not being printed which told me it was skipping its index.
import java.util.*;
public class DijAlg {
        static int source = 0;
        static Queue Queue = new Queue();
        static int NUMBEROFNODES = 4;
    public static void main(String args[]){
    Node NodeA = new Node("A"), NodeB = new Node("B"), NodeC = new Node("C"), NodeD = new Node("D");
    Node[] Nodes = {NodeA, NodeB, NodeC, NodeD};
    for (int i = 0; i< NUMBEROFNODES; i++){
     for (int v = 0; v< NUMBEROFNODES; v++){
         Nodes.dist[v] = 10000;
Nodes[i].previous[v] = 99;
Nodes[i].dist[source] = 0; // Distance from source to source
Queue.enqueue(NodeA);
Queue.enqueue(NodeB);
Queue.enqueue(NodeC);
Queue.enqueue(NodeD);
int i = 0;
while (!Queue.isEmpty()){
System.out.println(((Node)Queue.peek()).toString());
Queue.dequeue();
i++;
static class Node {
int [] dist;
int [] previous;
String name;
Node(String theName){
dist = new int [NUMBEROFNODES];
previous = new int [NUMBEROFNODES];
name = theName;
public String toString(){
String myString = name;
myString = myString.concat(" Dist ");
for(int i = 0; i < NUMBEROFNODES ; i++){
myString = myString.concat(String.valueOf(dist[i]) + ", ");
myString = myString.concat("Prev ");
for(int i = 0; i < NUMBEROFNODES; i++){
myString = myString.concat(String.valueOf(previous[i]) + ", ");
return myString;
class Queue {
     LinkedList list;
     // Queue constructor
     Queue()
          // Create a new LinkedList.
          list = new LinkedList();
     boolean isEmpty()
     // Post: Returns true if the queue is empty. Otherwise, false.
          return (list.size() == 0);
     void enqueue(Object item)
     // Post: An item is added to the back of the queue.
          // Append the item to the end of our linked list.
          list.add(item);
     Object dequeue()
     // Pre: this.isEmpty() == false
     // Post: The item at the front of the queue is returned and
     // deleted from the queue. Returns null if precondition
     // not met.
          // Store a reference to the item at the front of the queue
          // so that it does not get garbage collected when we
          // remove it from the list.
          // Note: list.get(...) returns null if item not found at
          // specified index. See postcondition.
          Object item = list.getFirst();
          // Remove the item from the list.
          // My implementation of the linked list is based on the
          // J2SE API reference. In both, elements start at 1,
          // unlike arrays which start at 0.
          list.removeFirst();
          // Return the item
          return item;
     Object peek()
     // Pre: this.isEmpty() == false
     // Post: The item at the front of the queue is returned and
     // deleted from the queue. Returns null if precondition
     // not met.
          // This method is very similar to dequeue().
          // See Queue.dequeue() for comments.
          return list.getFirst();
Here is the output
run:
A Dist 0, 10000, 10000, 10000, Prev 99, 99, 99, 99,
B Dist 0, 10000, 10000, 10000, Prev 99, 99, 99, 99,
C Dist 0, 10000, 10000, 10000, Prev 99, 99, 99, 99,
D Dist 0, 10000, 10000, 10000, Prev 99, 99, 99, 99,
BUILD SUCCESSFUL (total time: 2 seconds)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Similar Messages

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

  • 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

  • Problem with Queue Implementation

    Hi there !
    I can't solve the implementation of an exercize about Queue.My teacher wrote down just the interface Queue and the first part of the class ArrayQueue implementation.They are the following :
    public interface Queue<E>
       public int size();
       public boolean isEmpty();
       public E front() throws EmptyQueueException;
       public void enqueue (E element);
       public E dequeue() throws EmptyQueueException;
    public class ArrayQueue<E> implements Queue<E>
       public ArrayQueue(int cap)
          capacity = cap;
          Q = (E[]) new Object[capacity];
       public ArrayQueue()
          this(CAPACITY);
    }So the teacher asked to complete the code. I have tried and retried so many times for 3 days.I know it's so easy and I understood how it should work but when I try to write down the code I can't get the final solutions but only mistakes.
    During my attempts my better code was this :
    package queue;
    public class ArrayQueue<E> implements Queue<E>
         @SuppressWarnings("unchecked")
         public ArrayQueue(int cap)
            capacity = cap;
            Q = (E[]) new Object[capacity];
         public ArrayQueue()
            this(CAPACITY);
         public String toString()
            int count = 0;
            for(E element : Q)
                 return count +")"+(String)element;
            count++;
            return null;
         public void enqueue(E element)
              try
                   if(element == null)
                        throw new IllegalArgumentException();
                   if (size() == capacity)
                     throw new FullQueueException();
                   if(Q[rear] == null)
                      Q[rear] = element;
                      rear++;
              catch (FullQueueException e)
                   System.out.println("The Queue is Full !");
         public E dequeue() throws EmptyQueueException
              try
                 E temp;
                 if (isEmpty())
                      Q = (E[]) new Object[capacity];
                      front = 0;
                      rear = 0;
                     throw new EmptyQueueException();
                temp = Q[front];
                 Q[front] = null;
                 front++;
                 return temp;
              catch(EmptyQueueException e)
                   System.out.println("The Queue is Empty !");
              return null;
         public E front() throws EmptyQueueException
              try
                 if(Q[front] == null)
                           front++;
                 if (isEmpty())
                     throw new EmptyQueueException();
                 return Q[front];
              catch(EmptyQueueException e)
                   System.out.println("The Queue is Full !");
              return null;
         public int size()
              return (front + rear);
         public boolean isEmpty()
            return (front == rear);
        public Object[] getQueue()
            return Q;
         protected int capacity;
         public static final int CAPACITY = 1000;
         protected E Q[];
         protected int front = 0;
         protected int rear = 0;
    }But the problems are that I can add the element through the method enqueue() and delete it through dequeue() then,but after deleting it the array size is the same and when I print the array elements I see some null,so if I add a new element I get the message of the class FullQueueException because of the size which it's the same.
    Moreover if I delete all the elements and then I print the value returned by the method front() I get the NullPointerExceptionError because the returned value is null,but I think it should print it ! But he doesn't!
    How should I fix these problems ?
    I also wondered during all my attempts how to repeat this procedure after the array size limit is reached.What I really mean is if I delete the element Q[0] and the index front = 1 and rear = n - 1 for example,how can I add with the method enqueue() a new element in Q[0] again ?
    Can you help me courteously ?
    I hope my explanation was clear because of my English !
    Thanks in Advance !

    Thanks for all your suggestions men ^^ !
    I changed some things in the code :
    package queue;
    public class ArrayQueue<E> implements Queue<E>
         @SuppressWarnings("unchecked")
         public ArrayQueue(int cap)
            capacity = cap;
            Q = (E[]) new Object[capacity];
         public ArrayQueue()
            this(CAPACITY);
         public String toString()
              String s = "[";
              int count = 0;
              for (int i = front; i < rear; i++) {
                   count++;
                   s += Q.toString() + (i < rear - 1 ? "," : "");
              s += "] (" + count + " elements)";
              return s;
         public void enqueue(E element)
              try
                   if (size() == capacity - 1)
              throw new FullQueueException();
                   Q[rear] = element;
                   rear = (rear + 1) % capacity;
              catch (FullQueueException e)
                   System.out.println("The Queue is Full !");
         public E dequeue() throws EmptyQueueException
              try
              E temp;
              if(isEmpty())
              throw new EmptyQueueException();
         temp = Q[front];
              Q[front] = null;
              front = (front + 1) % capacity;
              return temp;
              catch(EmptyQueueException e)
                   System.out.println("The Queue is Empty !");
              return null;
         public E front() throws EmptyQueueException
              try
              if (isEmpty())
              throw new EmptyQueueException();
              return Q[front];
              catch(EmptyQueueException e)
                   System.out.println("The Queue is Empty !");
              return null;
         public int size()
              return (capacity - front + rear) % capacity;
         public boolean isEmpty()
    return (front == rear);
         protected int capacity;
         public static final int CAPACITY = 1000;
         protected E Q[];
         protected int front;
         protected int rear;
    }Now after I delete an element and I use the method enqueue() to add a new one the algorithm does,but
    after I delete all the elements I get an element null when I add the element in the array position n - 1.
    I have fixed the method toString() as pgt told me to do and it's really great,but dunno why sometimes when I delete an element it says the array has 0 elements also if the array is almost full !
    About my code changements,according to my university friend I should reduce front and rear mod the capacity and that's what marlin314 suggested me to do too and I had to change the expression if(size() == capacity) to if(size() == capacity - 1).But the algorithm doesn't work as it should do !                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Help in Queue Implementation

    Hello All
    I have to implement Queue ... i am able to implement enqueue and dequeue method .. but i am stuck to implement Reading Data from queue and and stroed it in String Array ..
    can any one have idea abt it.. if plz share sample code
    Ashish

    I have to implement Queue ... i am able to implement
    enqueue and dequeue method .. but i am stuck to
    implement Reading Data from queue and and stroed it
    in String Array ..If you are able to implement the dequeue method, how can you be
    stuck on reading data from the queue then? Can you show us some
    (relevant) code (between the proper code tags)?
    kind regards,
    Jos

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

  • Performance for messaging queue - queue implemented as single cache entry.

    Hey Brian/All,
    Has there been any progress on addressing the long standing performance issues with messaging?
    i.e. messaging stores a queue within a single cache entry, which means it needs to deserialize, add item, and reserialize every time we add an item to the queue.
    For push rep, this means a burst of data can bring messaging to it knees and cause a cluster to fall over (eg: a clear of a large cache, or a remote site that is unavailable causing queues to grow to a very large size).
    I have also noticed that when a queue gets very large, the jmx suspend/drain times out, and throws an exception.
    Cheers,
    Neville.

    Hi Friends,
    Create a function that needs to be called on the ejbCreate.
    Inside this function make the connections as in the snippet below and close it when ejbRemove() or exception.
    fis                          = new FileInputStream("D:/MessageRouter_UAT/AppConfig.Properties");
    props.load(fis);
    fis.close();
    String logPath      = props.getProperty("Log_path").trim()+".log";
    logHandler      = new FileHandler(logPath);
    logHandler.setFormatter(new SimpleFormatter());
    logWriter.addHandler(logHandler);
    logWriter.setLevel(Level.ALL);
    MQEnvironment mqEnv      = null;
    mqEnv      = new MQEnvironment();
    MQEnvironment.hostname      = props.getProperty("MQ_HOST_NAME").trim();
    MQEnvironment.port      = Integer.parseInt(props.getProperty("MQ_PORT").trim());
    MQEnvironment.channel      = props.getProperty("CHANNEL_NAME").trim();
    MQEnvironment.properties.put(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_CLIENT);
    q_Mgr                = new MQQueueManager(props.getProperty("QUEUE_MANAGER").trim());
    queueID                = q_Mgr.accessQueue(props.getProperty("ID_Queue").trim(), MQC.MQOO_OUTPUT);
    queueSG                     = q_Mgr.accessQueue(props.getProperty("SG_Queue").trim(), MQC.MQOO_OUTPUT);
    queueHK                = q_Mgr.accessQueue(props.getProperty("HK_Queue").trim(), MQC.MQOO_OUTPUT);
    queueCL                     = q_Mgr.accessQueue(props.getProperty("CL_Queue").trim(), MQC.MQOO_OUTPUT);
    Thanks,
    Arun Prithviraj

  • A bug in message pattern's queue implementation?

    Here is how to reproduce the problem.
    Have 2 Java program ready.
    A is to create a queue and publish 3 messages to the queue.
    B is to subscribe to the same queue and try to get all messages from the queue (put the getMessage inside a while(true) loop) then wait for new message.
    Step 1. Run A, which put 3 messages into queue.
    Step 2. Run B, which get 3 messages out of the queue then waiting on the getMessage() blocking call.
    Step 3. Kill program B without unsubscribe() call.
    Step 4. Run A, which put 3 messages into the queue again.
    Step 5. Run B, this time it only get 2 messages. The 1st message A put in on Step 4 got lost.
    Actually, if you run Step 2 multiple times before step 3, you will lost more message. It seems each time when there is a subscription created without a unsubscribe(), it will get one message lost.
    I know the propery way is to call unsubscribe(), but the JVM could be killed thus won't have time to do cleanup.

    Using message pattern 2.3, command pattern 2.3 and common 1.3
    Coherence version is 3.4.2.
    BTW, if the unit test program you mentioned is the MessageTests.java included in the src zip file, you won't be able to test this issue.
    All unit test inside the MessageTests.java are comsuming exactly number of messages been published then do unscribe() call.
    In order to reproduce this issue, you'd need to put your consumer JVM in a blocking getMessage() state (i.e. call getMessage() while there is no message in queue)
    then kill the JVM. The unit test codes in MessageTests.java never enter blocking wait state when call getMessage().
    Example code -
    For the one putting message
    MessagingSession messagingSession = DefaultMessagingSession.getInstance();
    Identifier topicIdentifier = messagingSession.createQueue("test-queue");
    messagingSession.publishMessage(topicIdentifier, "Hello WorldY1");
    messagingSession.publishMessage(topicIdentifier, "Hello WorldY2");
    messagingSession.publishMessage(topicIdentifier, "Hello WorldY3");
    messagingSession.publishMessage(topicIdentifier, "Hello WorldY5");
    messagingSession.publishMessage(topicIdentifier, "Hello WorldY5");
    messagingSession.publishMessage(topicIdentifier, "Hello WorldY5");
    messagingSession.publishMessage(topicIdentifier, "Hello WorldY5");
    messagingSession.publishMessage(topicIdentifier, "Hello WorldY5");
    messagingSession.publishMessage(topicIdentifier, "Hello WorldY5");
    messagingSession.publishMessage(topicIdentifier, "Hello WorldY1");
    messagingSession.publishMessage(topicIdentifier, "Hello WorldY2");
    messagingSession.publishMessage(topicIdentifier, "Hello WorldY3");
    For the one getting message
    MessagingSession messagingSession = DefaultMessagingSession.getInstance();
    Identifier topicIdentifier = messagingSession.createQueue("test-queue");
    Subscriber subscriber = messagingSession.subscribe("test-queue");
    while (true) {
    String message = (String)subscriber.getMessage();
    System.out.println(message);
    }

  • Need help in Queue Implementation

    MyQueue
    public class MyQueue {
         private int start, end;
         private int[] qArray;
         private int size;
         MyQueue(int size){
              this.size = size;
              qArray = new int[size];
              start = end = -1;
         public int removeFromQueue(){
              int retVal = -1;
              if(isEmpty()){
                   System.out.println("Queue is empty");
              }else{
                   retVal = qArray[++start];
              return retVal;
         public void addToQueue(int element){
              if((end+1) < size ){
                   qArray[++end] = element;
              }else{
                   System.out.println("Queue is full. Please flush out someone");
         private boolean isEmpty(){
              return (start==end);
         public String toString(){
              StringBuffer buffer = new StringBuffer();
              for(int i = start; i< end; i++){
                   buffer.append(qArray[i]+" ");
              return buffer.toString();
    MyQueueImpl
    public class MyQueueImpl {
         public static void main(String args[]){
              MyQueue myQueue = new MyQueue(10);
              for(int i = 0; i< 10; i++){
                   myQueue.addToQueue((int)(i+ Math.random()));     
              System.out.println(myQueue);
              System.out.println("Removing 3 guys from the queue");
              System.out.println(myQueue.removeFromQueue());
              System.out.println(myQueue.removeFromQueue());
              System.out.println(myQueue.removeFromQueue());
              System.out.println("Adding 10 to the queue");
              myQueue.addToQueue(10);
              System.out.println(myQueue);
              System.out.println();
    }

    public class MyQueue {
         private int start, end;
         private int[] qArray;
         private int size;
         MyQueue(int size){
              this.size = size;
              qArray = new int[size];
              start = end = -1;
         public int removeFromQueue(){
              int retVal = -1;
              if(isEmpty()){
                   System.out.println("Queue is empty");
              }else{
                   retVal = qArray[++start];
              return retVal;
         public void addToQueue(int element){
              if((end+1) < size ){
                   qArray[++end] = element;
              }else{
                   System.out.println("Queue is full. Please flush out someone");
         private boolean isEmpty(){
              return (start==end);
         public String toString(){
              StringBuffer buffer = new StringBuffer();
              for(int i = start; i< end; i++){
                   buffer.append(qArray[i]+"   ");
              return buffer.toString();
    }public class MyQueueImpl {
         public static void main(String args[]){
              MyQueue myQueue = new MyQueue(10);
              for(int i = 0; i< 10; i++){
                   myQueue.addToQueue((int)(i+ Math.random()));     
              System.out.println(myQueue);
              System.out.println("Removing 3 guys from the queue");
              System.out.println(myQueue.removeFromQueue());
              System.out.println(myQueue.removeFromQueue());
              System.out.println(myQueue.removeFromQueue());
              System.out.println("Adding 10 to the queue");
              myQueue.addToQueue(10);
              System.out.println(myQueue);
              System.out.println();

  • Examples for JMS Error Queue implementation in BPEL

    Hi ,
    Please anyone provide me examples for JMS error queue implementaion in BPEL.
    Regards
    Narsi p

    Hi Narsi p,
    Please remember to mark answers accordingly... Helpful or correct, following the forum rules
    https://forums.oracle.com/forums/ann.jspa?annID=330
    Can you tell us more about what are you trying to achieve here?
    If you are just trying to configure an error queue to put the messages that couldn't be delivered, you can do this in weblogic directly.
    Configuring an Error Destination for Undelivered Messages
    http://docs.oracle.com/cd/E17904_01/web.1111/e13727/manage_apps.htm#JMSPG254
    Cheers,
    Vlad

  • Adding user-created objects to an Array

    I would be grateful if anyone can help me. I have created the following class:
    import java.util.*;
    * Created on 08-Dec-2005
    * @author Hussein Patwa
    public class room {
        public String roomName;
    // String to hold the room name
        public static void main(String[] args) {
        String roomName;
        // Temp string to hold room name
        LinkedList objectqueue = new LinkedList();
        // Queue implementation to hold list of objects in room
        LinkedList stack = new LinkedList();
        // Stack implementation to hold objects held by user
    public void enterRoomName(String roomName) {
        // Method to allow entering of the room name
        this.roomName = roomName;
        // Assignment the room name to the roomName field
    public void viewRoomName() {
        // Method to allow the viewing of the room name
        System.out.println("This is the " + roomName + " ");
        // Print the room name
    }I also have a main class:
    import java.util.*;
    * Created on 08-Dec-2005
      * @author Hussein Patwa
    public class start extends room {
        public static void main(String[] args) {
      String gameName = "PatwaMaze";
      // Field to hold the game name
      room[] roomList = new room[6];
      // Create a new array to hold the rooms
    public void startGame() {
    roomList.add["Kitchen"];
    roomList.add["Parlour"]
    roomList.add["Lounge"]
    roomList.add["Stairs"]
    roomList.add["Chamber"]
    roomList.add["Study"]
    }I want to create an array of room objects, or would it be more correct to say object references, and then have their labels as the room name, which would be stored in that room's roonName field. So then I can iterate through the list, and print out each room's roomName field thus giving a list of the rooms. So (and I hope this is making sense), I need to add the rooms to the array, set each room's rromName field and then iterate through it. But I'm not sure of the syntax to add the room's name and the array index.
    BTW, I have done quite a bit of searching for this, as well as looked through several texts, so I am posting here because i'm not sure where to go next.
    Thanks.
    Hussein.

    Short answer: There's no add method. That woul be in a Collection.
    http://java.sun.com/docs/books/tutorial/collections/
    For an array, it's arr[0] = something;
    arr[1] = somethingElse;
    / / etc.

  • Can't initialize queue

    I need to sort an array of File and then copy it into a queue, I need this queue to be global.
    Let queue be _sortedDateQueue.
    How can I do this, here is the method of my class which uses it:
    public Queue sortArrayByDate(File[] allfiles)
              Arrays.sort(allfiles, new Comparator()
                   public int compare(Object o1, Object o2) {
                   File f1 = (File)o1;
                   File f2 = (File)o2;
                   return ((Long.valueOf(f1.lastModified())).compareTo(Long.valueOf(f2.lastModified())));
    for(int i=0; i < allfiles.length ; i++)
                   _sortedDateQueue.offer(allfiles); // I am getting null ointer exception here
                   System.out.println("Sorted Queue :" + _sortedDateQueue.peek());
              for (Iterator iter = _sortedDateQueue.iterator(); iter.hasNext();)
                   File element = (File) iter.next();
                   System.out.println("Sorted Queue :" + element.getName());
              return _sortedDateQueue;
    How can I intialaize queue as its an interface?

    you just create an object of some class that you prefer which implements Queue; for example, here I use LinkedList
    Queue<File> _sortedDateQueue = new LinkedList<File>();also when you add to it you probably wanted
    _sortedDateQueue.offer(allfiles);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Confused newbie with queue problems

    I real new to java programming and I am trying to write a program which will queue objects. It needs to be FIFO and resize itself automatically. I can find a Queue class in C# but seeing as I'm writing in Java it's not very useful.
    I'm sure it's just me not looking in the right place but I would be really grateful if anyone could push me in the right direction.

    Hi,
    You can use a list to emulate a queue. Just items to the end of the list, and take items from the beginning of the list. There are several different list implementations.
    I would use a LinkedList in this case:
    http://java.sun.com/j2se/1.4.2/docs/api/java/util/LinkedList.html
    There is also a queue implementation in jdk 1.5. What java version do you use?
    /Kaj

  • Queue with Iterator

    How hard is to implement an Iterator in a Queue?

    Most people in these forums would never bother. They'd just use the LinkedList in the API and get on with life.
    That said, most of us did do the hard work of writing our own (mine was back in the days of Turbo Pascal) - so we understand how the API LinkedList is implemented.
    So, let's turn this around and make into a question for YOU: Given your knowledge of how linked lists are implemented, what challenges do you think there would be in implementing an iterator for it?
    Ensure that your answer accounts for changes that may be made to the queue while the iterator is still active.
    I'm going to set a watch on this topic - if you reply and give a good shot at the answer, I'll see if I can provide some things for you to think about.
    Cheers!
    - K

  • Queue of Queues

    Hey, everybody! I'm trying to do something fairly simple but I'm running into a little trouble with it.
    I'm trying to simply make a queue of queues. I can make the actual container, but when it comes time to add a new queue to the main queue, it gives me the error:
    WorldGen.java:16275: java.util.Queue is abstract; cannot be instantiated
    kingdoms.add(new Queue<Queue<Point>>());
    ^
    1 error
    Here's the implementation of the method I used:
    private static void generateKingdoms(int width, int height)
              // create a queue of queues of kingdom "points" for each palace
              Queue<Queue<Point>> kingdoms = new LinkedList<Queue<Point>>();
              // create an array of randomized colors to be used as the kingdoms' boundary colors
              int colorArray[] = new int[numPalaces];
              // search the entire image for all of the palaces
              for (int y = 0; y < height; y++)
                   for (int x = 0; x < width; x++)
                        if (getPixel(x, y) == PALACE)
                             kingdoms.add(new Queue<Queue<Point>>());
         }I understand the Queue is an abstract class and needs to be interfaced with a LinkedList type, but when I put make the queue add a LinkedList object instead of a Queue, it states that the interface is looking for a Queue. A workaround or some advice would be greatly appreciated :] Thank you!
    Colton

    T.PD wrote:
    coltonoscopy wrote:
    and I found that I had messed up not on line 4,Didn't I say "look at line 4 and learn from it"? At least that's what I ment... You did, and my sentence there acknowledged that I understood that. I just don't think you caught the "not" there toward the end of the quoted part of that sentence. The rest of that sentence following what's quoted then made it clear that I found the problem on line 31 instead. I apologize if my own speech there wasn't clear or if it left room for misinterpretation.
    Anyways, thanks again! :]
    Colton

Maybe you are looking for

  • After upgrading to mavericks, all my downloaded apps crash

    Hey guys- I upgraded to mavericks 2 days ago and love the os and the look and feel. the thing is, i have a bunch of downloaded apps like openoffice and parallels desktop and after the appstore upgrade, the apps just plain freeze up. Any ideas on how

  • Black screen appears after exporting to Quicktime movie

    I'm having trouble exporting a time-lapse video to a QT movie. The screen is always black when I try to watch the finished product. Here's what I'm doing: I import the jpeg files into QT 7 Pro using "Open Image Sequence." At this point I'm able to wa

  • CCMS Auto-Reaction for custom Local Monitor Set in RZ20

    Since I am not able to modify any SAP made monitor sets I have had to make a copy of them and place them under a new heading and then I can add the systems I want to monitor. Once I make that copy though, I want to add an auto-reaction to the set but

  • SDK apps

    Are there any SDK apps available yet? Where do we find them? If not, what's taking so long? Can't wait.

  • Open explorer in document library is not working randomly sharepoint 2013

    In a SharePoint document library open explorer is not opening. If i will open in fresh browser it is opening for sometime but after browsing sometime it will not open and show the message as below. I check there are default managed path are there roo