codingenious
codingenious

Reputation: 8663

Check size of sun.misc.Queue

My project is using a Queue by extending sun.misc.Queue and I need to know size of this queue every second.

As sun.misc.Queue does not provide size method API. I tried to add toString method to my class extending sun.misc.queue, and calling the toString in a seprate thread dedicated for printing the queue every second.

public String toString()
{
    int count = 0;
    Enumeration er = null;
    synchronized (this)
    {
        er = myQ.elements();

        while (er.hasMoreElements())
        {
            count++;
        }
    }
    return "" + count ;
}

myQ is field in this class.

But this ain't working too. After I add this code, complete system goes for toss.

Can anybody help in identifying if I am doing something wrong.

Upvotes: 0

Views: 359

Answers (2)

Xabster
Xabster

Reputation: 3720

Disclaimer: do not use reflection unless you have to.

    Queue q = new Queue();
    Field f = Queue.class.getDeclaredField("length");
    f.setAccessible(true);
    int size = f.getInt(q);
    System.out.println(size);

I read your question again... now I'm mad at you for just writing "goes for toss". Stacktrace or GTFO.

Upvotes: 0

Tim B
Tim B

Reputation: 41210

Use the standard java Queues (LinkedList for example is designed to be able to use it as a dequeue). They provide a size method.

Alternatively you could over-ride the various add/remove methods and keep a counter internally so you always know the size. You would be better off just using the right tool for the job though.

Upvotes: 1

Related Questions