Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better LinkedBlockingQueue unbounded or LinkedBlockingQueue with capacity [closed]

I am using LinkedBlockingQueue as workqueue in ThreadPoolExecutor. Problem is shall i use bounded LinkedBlockingQueue or unbounded LinkedBlockingQueue. I have overridden execute method of ThreadPoolExecutor and no longer facing the problem of thread creation after core pool size.

So please tell me which will be better one to use LinkedBlockingQueue bounded or unbounded.

Thanks, Tushar

like image 586
Scientist Avatar asked Oct 15 '13 06:10

Scientist


People also ask

Is blocking queue thread-safe?

BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control.

What is the max capacity of a Java BlockingQueue?

Here we have a blockingQueue that has a capacity equal to 10. It means that when a producer tries to add an element to an already full queue, depending on a method that was used to add it (offer(), add() or put()), it will block until space for inserting object becomes available. Otherwise, the operations will fail.

What creates a new unbounded queue?

newFixedThreadPool uses new LinkedBlockingQueue which has not limit for tasks to be accepted. When new task arrives, and there is no thread available it goes to the queue. Tasks can be added to the queue indefinitely causing OutOfMemoryError .

What is bounded queue and unbounded queue?

Bounded Queues are queues which are bounded by capacity that means we need to provide the max size of the queue at the time of creation. For example ArrayBlockingQueue (see previous example). Unbounded Queues are queues which are NOT bounded by capacity that means we should not provide the size of the queue.


1 Answers

Unbounded queue is secure way to ensure no task is rejected, or use bounded queue with such a capacity that is so large that it is capable of holding maximum number of tasks that can come in your application. That depends on design of your application. I think if you understand(discuss with architect) application design, you would be able to decide upon size of queue. And about memory and CPU, unless you add tasks to the queue, they wont increase, and will be same for both - unbounded or bounded. (Tested in demo application)

public static void main(String[] args)
{
   LinkedBlockingQueue<Runnable> r = new LinkedBlockingQueue<Runnable>(11);

  while(true)
  {
     //    r.offer(new Task(1));
  }
}

just play around with size to check.

like image 179
codingenious Avatar answered Sep 30 '22 20:09

codingenious