Joker
Joker

Reputation: 11154

LinkedBlockingQueue and PriorityBlockingQueue in ThreadPoolExecutor

I am working on thread pool executor, I obeserverd when i use PriorityBlockingQueue it throws ClassCastException in code below and every things works fine if I choose LinkedBlockingQueue instead of PriorityBlockingQueue in code below.

Please help me understand this .

public class Test1 {
        public static void main(String[] args) {
            ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 10, TimeUnit.MINUTES, new PriorityBlockingQueue());
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            executor.submit(new Runnable() {
                @Override
                public void run() {
                }
            });
            executor.submit(new Runnable() {
                @Override
                public void run() {
                }
            });
        }

    }

Upvotes: 0

Views: 283

Answers (1)

GaurZilla
GaurZilla

Reputation: 373

In case of PriorityBlockingQueue whenever user inserts the specified element into the priority queue, ClassCastException is thrown, if the specified element cannot be compared with elements currently in the priority queue according to the priority queue's ordering.

However, There is no comparator required for LinkedBlockingQueue. So, there was no any exception.

Moreover, you can verify the same in the

LinkedBlockingQueue.offer() and PriorityBlockingQueue.offer() methods for more understanding.

Upvotes: 2

Related Questions