Java Concurrency Interview: Implement Producer Consumer pattern using wait-notify

Java Concurrency Interview: Implement Producer Consumer pattern using wait-notify

Defog Tech

5 лет назад

139,583 Просмотров

Ссылки и html тэги не поддерживаются


Комментарии:

Defog Tech
Defog Tech - 14.03.2019 07:53

Important: The last part about using wait-notify is incorrect. My mistake, sorry about that.

The object used to wait/notify should be the same object used by threads to synchronize. So correct code should be similar to:

synchronize(sharedQ){
sharedQ.wait();
}
synchronize(sharedQ){
sharedQ.notifyAll();
}

That was a basic mistake which I should have caught. I feel bad about misleading the initial viewers. Sorry.

Ответить
Gauri Kesarwani
Gauri Kesarwani - 23.10.2023 14:38

It would be more helpful if you provide the sample code or example code link. Thanks for such a nice video!

Ответить
Venkataramana N
Venkataramana N - 04.10.2023 14:58

Hi @Defog
Why there is no while condition on put method
It will have the same problem in adding the item in max index position

Pls correct me if iam wrong

Ответить
Сергей Сергеев
Сергей Сергеев - 23.09.2023 00:01

Greetings from Russia , having watched hours of content on concurrency/multithreading , this is the by far the best one i have seen , top notch.

Ответить
radhi anand
radhi anand - 03.07.2023 17:33

first time learning about producer-consumer. your explanation is very clear and easy to understand

Ответить
The UnUsual
The UnUsual - 21.04.2023 12:32

Just AMAZING.

Ответить
Arek
Arek - 11.04.2023 16:14

I love your tutorials! I did this example myself and found a little but meaningful bug:
-notEmpty and notFull should be called ".signal()" instead of ".signalAll()" because in case of releasing one spot in the queue by take() method, if there are multiple "putting" Threads, they are all notified at once about free space and they add concurently its own item exceeding the maxSize (and later condition `queue.size() == max` doesn't catch situation when this size is exceeded)

Ответить
NISHANK DAS
NISHANK DAS - 11.04.2023 14:39

I still don't understand how can two consumer threads wait on the condition because we have been using a lock over that method in the first place.

Ответить
J
J - 26.01.2023 05:53

notEmpty and notFull not needed ..we can just use this.wait()... this implementation throw java.lang.IllegalMonitorStateException: current thread not owner... i tried it..

Ответить
Sai Kamireddy
Sai Kamireddy - 07.11.2022 04:13

Why does java releases the lock when lock state is false. does this allow multiple threads to come in and wait? Because of this we need to solve the problem where multiple consumers trying to read the same item.

Ответить
DZ Hero
DZ Hero - 16.09.2022 01:36

Hi Mate; error correction: you should use notEmpty.signal() and not notEmpty.signalAll()

Ответить
natureBoy6
natureBoy6 - 20.08.2022 22:38

I don't understand if there was a lock, how did two threads enter the method?

Ответить
Jwork
Jwork - 10.08.2022 12:38

Very well explained thank you !

Ответить
Torrtuga Nooh
Torrtuga Nooh - 09.08.2022 10:31

If we are taking same lock in both put and take method, then wouldn't it be that only one thread will do either put or take.

If a thread is in put, no thread can go in take. And vice versa.

Is that possible?

Ответить
SHUBHAM VISHNOI
SHUBHAM VISHNOI - 06.08.2022 21:52

Clear explanation!!

Ответить
Mir Taqee
Mir Taqee - 01.06.2022 21:22

Thanks

Ответить
Chris Athanas
Chris Athanas - 26.05.2022 06:20

Best clear explanation of a very complicated subject

Ответить
HARI S14
HARI S14 - 20.05.2022 15:14

A perfect explanation I had ever seen. Thanks a lot!

Ответить
sanjay Paudel
sanjay Paudel - 03.04.2022 10:27

Bro you are best guru out there . Put more contents your channel will bloom

Ответить
Breeze Misty
Breeze Misty - 21.03.2022 20:51

Bro, you rock. tks a lot!

Ответить
SrinivasaRao Kandibanda
SrinivasaRao Kandibanda - 17.03.2022 08:42

I have similar problem where two threads need to read element by element.. i tried same concept but will not work. Two threads started but not moving further

Ответить
SRV SRVM
SRV SRVM - 12.02.2022 15:59

Neat and clear explanation...

Ответить
Hari G S
Hari G S - 23.01.2022 08:21

@9.04, how two thread could come at that point since we called lock above. I think only one thread will be in await and when the notEmpty.signalall is called that thread will remove the item and call the unlock so the other thread can come inside and do the if check and can go to the await state. What is the need to while there?

Ответить
ajeet singh
ajeet singh - 16.01.2022 13:20

Since a long time no video, as you have also switched to new job, pls start creating new videos

Ответить
Saravanan Sivakumar
Saravanan Sivakumar - 15.01.2022 12:23

I am getting illegalMonitorstateException. Any idea when it occurs? I followed the same approach.

Ответить
Deepak Kumar
Deepak Kumar - 30.12.2021 08:59

could have been better if the live coding was done for the example

Ответить
Raj G
Raj G - 08.12.2021 08:21

Another Gem of a video from you on java Concurrency. I've a question though, How does changing if condition to while would solve the problem ? Can you please elaborate ?

Ответить
shubhodeep paul
shubhodeep paul - 05.12.2021 14:25

can anyone please help me with this code
it is throwing illegal monitor state exception
class CustomBlockingQueue{
Queue<Integer> q=new PriorityQueue<>();
Lock lock= new ReentrantLock();
int max=10;
Condition full=lock.newCondition();
Condition empty=lock.newCondition();
void add() throws InterruptedException {
while (true){
lock.lock();
try{
if(q.size()==max){
empty.await();
}
q.add(1);
full.signalAll();
System.out.println("adding element");
}finally{
lock.unlock();

}
}
}

void remove() throws InterruptedException {
while (true){

lock.lock();
System.out.println("remove aqquireing lock");
try{
System.out.println(q.size());
if(q.size()==0){
System.out.println("waiting");
full.wait();
}
q.remove();
empty.signalAll();
System.out.println("removing element");
}finally{
lock.unlock();

}
}

}

}

public class Main {
public static void main(String[] args) throws InterruptedException {
CustomBlockingQueue customBlockingQueue=new CustomBlockingQueue();
new Thread(()-> {
try {
customBlockingQueue.add();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(()->{
try {
customBlockingQueue.remove();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();

}
}

Ответить
balanjaneyulu p
balanjaneyulu p - 02.12.2021 04:39

Great videos. it makes it easy to understand complex concepts. Though I have confused about using the while loop instead of the If condition. It could have been better to explain issues with if condition here and then introduce a while loop. anyway amazing explanation with exaples

Ответить
Senthil
Senthil - 19.10.2021 20:59

Hi Deepak, Please start posting new videos. Your way of explaining the things in simple language helps to understand the concepts better. Great job! Looking forward to learn from your new videos

Ответить
Sourav Sarker
Sourav Sarker - 30.09.2021 20:42

Great explanation on producer and consumer using different ways. It makes the idea really clear. I was wondering if there is any way to handle the fairness for consumers meaning if any consumer goes to wait-state first he will be notified first.

Ответить
Aatif Nazar
Aatif Nazar - 12.09.2021 21:05

this video has cleared a lot of my doubts and the way you have explained will help me remembering it for a very very long time ! Thanks for your hard and crisp work !

Ответить
rohan sinha
rohan sinha - 10.08.2021 01:27

GENIUS !! No other words. Such a smooth and clear explanation to the problem

Ответить
வெற்றி வேல்
வெற்றி வேல் - 29.07.2021 17:46

I like to add my humble opinion here. The while loop in the "take()" may allow N number of threads to enter the next line and which is removing the element. The first thread will remove the element successfully but the remaining threads will be ends up in Null. I would suggest using a slightly modified "Observer design pattern".

Ответить
Sashi Kant Shaw
Sashi Kant Shaw - 29.07.2021 07:37

At 9th min, where you replaced "if" with a "while", I personally feel its unnecessary, because the second thread will go in await as the queue.size() will be 0. It will not get any null value or I am missing something.

Ответить
GMath
GMath - 29.07.2021 04:01

Thanks!

Ответить
Mandeep sharma
Mandeep sharma - 21.07.2021 12:11

Option 3 with semaphore would have been great. Thank you.

Ответить
Mayank
Mayank - 01.06.2021 06:25

I really want to thank you for this video, It taught me a lot of things Blocking queue, await-signal, wait-notify.
But at the same time, the last mistake wasted a lot of time of mine. I should have seen this comment earlier.

If possible, can you please mention this on the video itself. Maybe as some floating suggestion.

Ответить
Indigo
Indigo - 20.05.2021 21:45

You made it so easy to understand. Thank you very much!

Ответить
naveen kumar
naveen kumar - 10.05.2021 07:12

you are the best.. please keep up doing the good work..

Ответить
Tannu Bajpai
Tannu Bajpai - 09.05.2021 11:18

Thanx u bro
very nice explanation.

Ответить
marshall bruce
marshall bruce - 18.04.2021 06:13

Thabk you

Ответить
Manish Maithani
Manish Maithani - 17.03.2021 05:42

Which is the better way of implementation of blocking queue? "Lock and Condition" or "Wait-Notify" and why?

Ответить
Kunal Budhiraja
Kunal Budhiraja - 08.03.2021 12:07

This channel teaches more about the approach to solving the problem.They don't go to the solution straight away,first they come to common implemented pattern ,than they optimize the solution.
Brilliant

Ответить