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?

Ana Maria
  • 475
  • 2
  • 11
  • 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. – Michał Krzywański Aug 26 '20 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) – Ana Maria Aug 26 '20 at 18:18

1 Answers1

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

Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63
  • Does it mean that here linkedList will actually take less space? Even though 1 node is more expensive than 1 element in array? – Ana Maria Aug 26 '20 at 18:22
  • @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. – Janez Kuhar Aug 26 '20 at 18:30
  • @JanezKuhar Actually it doesn't. I am learning Java and I am very detailed :) That is why I ask these stuff. – Ana Maria Aug 26 '20 at 18:32
  • 1
    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. – Michał Krzywański Aug 26 '20 at 18:40