educative.io

Blocking queue size is given 5, After running the entire program, I could see 6 enqueue operations in first place?

Can this scenario be elaborated?

Hi @abhijeet_patwari,

Thank you for reaching out to us. Since we can’t predict the behavior of a Thread and this output appears to be as when the q.enqueue(i) was executed till i=4. There was a possible context switch and it moved to thread 2 and performed q.dequeue() and when thread 2 notifyAll() the context was switched again to thread 1 and performed q.enqueue(i). After performing q.enqueue(i) the context was switched and printed the first dequeue message and then performed the other q.dequeue() and then again context is switched again.

If you run the code multiple times, it will give you different outputs but if you want the enqueue and dequeue messages to be synchronized then put these print statements in synchronized block in both enqueue() and dequeue() methods.

I hope I have answered your question but if there seems to be any confusion then please do let me know.