1

Say I make capacity of arrayBlockingQueue and linkedBlockingQueue both to 100. I add only 10 elements in each of them.

Will array hold full capacity even though 90 elements are empty? I mean would it have 10 elements and 90 nulls? Another thing, how would linked behave in this case? Would it have 10 or 100 nodes? And would there be 90 'null value nodes'?

Can someone explain me this? How do they behave in this case?

2
  • 3
    In case of ArrayBlockingQueue it will create an array of size 100 and 10 elements, rest will nulls. In case of LinkedBlockingQueue only 10 nodes will be created - the capacity here is used as a limitation to create so called bounded queue with maximum entries limit. Commented Aug 26, 2020 at 18:16
  • So I can sum that even thought 1 element in array takes less space than 1 node (because it has next,previous,value), in this case linked would be more effective? As it doesn't store all 100 nodes, whereas array stores 100 references? (If I can say null is reference) Commented Aug 26, 2020 at 18:18

1 Answer 1

3

In case of ArrayBlockingQueue it will create an array of size 100. It will contain 10 elements that you inserted and the rest will be null.

In case of LinkedBlockingQueue only 10 nodes will be created - the capacity here is used as a limitation to create so called bounded queue with maximum entries limit (in multithreaded environment it might be handy to not get out of memory).

Sign up to request clarification or add additional context in comments.

4 Comments

Does it mean that here linkedList will actually take less space? Even though 1 node is more expensive than 1 element in array?
@AnaMaria Perhaps the more important question might be: "Why does that matter in your application/use case?" We are at the level of micro-optimisation here.
@JanezKuhar Actually it doesn't. I am learning Java and I am very detailed :) That is why I ask these stuff.
To measure this you would have to check exact space (for example for the array that is backing the ArrayBlockingQueue it would probably be 8 + 4 + 100 * 4 bytes but it will also depend on the JVM used). For a LinkedBlockingQueue it would be 4 + 4 (item and next) for the references of the node + some bytes for object header.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.