Java Fundamentals - Lesson 48 - wait(), notify() and using volatile

preview_player
Показать описание
Are you new to Java development? Do you want to know what to start with? This is a complete stream dedicated to you - the junior developer or future developer.

- Java OCP 11 certification
- Learn Java basics
- Find a junior java developer role

If your target is at least one of the above, then this lesson streaming is for you. Join!

Don't forget to follow me on Twitter @laurspilca or LinkedIn for more posts and discussions.

Code on GitHub:

and

Рекомендации по теме
Комментарии
Автор

I will be using the knowledge you just teach in your multithreading sessions pretty soon, and feel much more comfortable to make a good usage of it now. Again keep the good work! Cheers mate.

bmiguelmf
Автор

Hello Mr Spilca. Excelent content.
If you call wait() or notify() outside of a synchronized block you will get a RuntimeException.

pericopalotes
Автор

About the monitor part, I understand it now. Thank you for visualize the process. Also will you plan to cover about concurrent collections

sva
Автор

Thanks as always!
I only have a concern regarding the intrinsic lock. When a thread completes the execution of a synchronized block, does the thread automatically release the lock or does the JVM decide when thread will release it ?
Because you mentioned in the video that a consumer thread c1 will execute the synchronized block repeatedly for a period of time. I am just wondering how c1 is able to execute the synchronized block again in a row when other threads like c2 and producers p1 and p2 are also the candidates of the same intrinsic lock.

AliHassan-bzsk
Автор

Hi Sir
Can you suggest practice questions list for all threads related concepts? Also suggest link for @async in Spring boot

DAYANANDJHA
Автор

Hi Laur! Thanks for the great lessons again! Does shared resource always have to be static?

Another question; you mentioned if the condition is false(bucket is empty) we somehow let producer enter the stage. So since when the condition is false, won't consumer thread will get out the synchronized block anyway? And since out of the synchronized block, when it's in the while loop can't producer enter the synchronized block?

public class Consumer extends Thread {

public Consumer(String name) {
super(name);
}

@Override
public void run() {
while (true) {
// not sync
// Tx
synchronized (Main.bucket) {
if (!Main.bucket.isEmpty()) {
int n = Main.bucket.get(0);
Main.bucket.remove(0);

+ " took out the value " + n + " from the bucket");
}
}

// not sync
}
}
}

public class Producer extends Thread {

public Producer(String name) {
super(name);
}

@Override
public void run() {
Random r = new Random();
// 100 wait() notify()

// scja / scjp -> oca8 / ocp8 -> ocp I 11 / ocp II 11
while (true) {
synchronized (Main.bucket) {
if (Main.bucket.size() < 100) { // T1
int n = r.nextInt(1000); // [0, 999]
Main.bucket.add(n);

+ " added value " + n + " to the bucket");
}
}
}
}
}

Rocky_
Автор

Thanks, @laurspilca When using the wait() method, I saw something unexpected. The thread that was in the waiting state, however, was automatically notified after some time, even though I didn't make the use of notify() method in my code. How is this possible that a thread is being notified automatically ?

AliHassan-bzsk
Автор

Hi Laurentiou,
Thank you for the outstanding content.

I experimented with your code and everything works fine but I would like to ask you:
a) I still fail to understand why this.wait does not work ( it produces exceptions as you said). I mean as I get it, the current thread "listens to itself" and stops as it would listen to the "policeman". And if there is noone else but the thread that has now taken control and is the new current thread who "awakens" all, how can any thread be "awakened" at the wrong time?

b) IntelliJ gives me a warning: "Synchronization on a non-final field 'Main.bucket' ". Should this be a concern?

appanta
Автор

Hello Laurentiu! I have a few questions

1). When the JVM prematurely suspends a thread to schedule another thread..then does the suspended thread relinquish the locks it has acquired?
If it does release the locks then isn't there a chance of inconsistent data modification of shared data?

And if it doesn't release the lock, then what happens if a lot of the threads that are in runnable state also need to acquire the same lock? Does JVM waste CPU cycles till we eventually resume the original thread or does it have some kind of an optimization by which it finds out that the runnable threads also require the same lock and hence should not be scheduled?

2). In our previous producer-consumer example, we synchronized the methods using the bucket monitor. In the logic of both producer and consumer, when we check the size of array, then isn't it possible that both are seeing their own cached values? Producer will fill it's own cached bucket and keep waiting infinitely and the consumer will keep reading it's cached empty bucket array and keep waiting infinitely till the values are in sync again?

Adi-yiqq
Автор

Hey!
I have a question to 24:25. Why did you use try-catch for so many lines? Shouldn't you put try-catch only on `Main.bucket.wait()` method?

beznerwow
Автор

Hi Laurentiu, yif I undersand you correctly, you can have 1 producer with a bucket foll of ints an you can have various consumers pulling from that bucket.... For example I can have c1, c2, c3, c4, c5.... and all pull from the same Producer or do I need to have one producer and one consumer?
For example: You have a grocery cart and everything goes in their, but when it is time to pay all the consumers (family members) pull their own stuff like the candy, popcorn, cokes, ... etc... is that correct?
The example you gave:
you have 2 producers and one bucket... both producers are putting the ints in the same bucket? producer1 puts in int:15 and producer2 puts in: int 100, and so on... is this correct?
If so then the consumers (kids) come around and take out int 15 another takes out int:100 ... etc...
AM I understanding this correctly...

I understand we can't know who is next on line if it is a producer or consumer, but running the program. I get the following outputs...
I gather it doesn't just do one operation but various at one time... I was thinking ... I would see one then the next ...
something like c1, p2, p1, c2, c1, .... I get large output of each...


c2 took out value 98 from the bucket.
.
.
.
c2 took out value 458 from the bucket.
c2 took out value 363 from the bucket.
c2 took out value 40 from the bucket.
p1 added 921 to the bucket.
p1 added 150 to the bucket.
p1 added 81 to the bucket.
.
.
.
p1 added 131 to the bucket.
p1 added 89 to the bucket.
c1 took out value 921 from the bucket.
c1 took out value 150 from the bucket.
.
.
.
c1 took out value 221 from the bucket.
c1 took out value 89 from the bucket.
p2 added 32 to the bucket.
p2 added 137 to the bucket.
.
.
.
p2 added 743 to the bucket.
p2 added 708 to the bucket.

peterfraga
Автор

If we use the monitor and only one synchronized block runs at a time, wouldn't that essentially be sequential programming?

sitalsitoula
Автор

Hello! At 20:10 why do you say the producer tests the condition again and again? I have to admit, I didn't test your example, but at least based on what I can see, the loop is not inside the synchronized block. So the condition is simply tested, it is false, then exits the synchronized block, making it available for another thread. As you said, the space between the while instruction and the synchronized keyword is not synchronized. How would it be different if we would have added the while instruction inside the synchronized block?

Hulethepenguin
Автор

Dear Laurentiu. I am very sorry that I disturb you, but I have a question. Let's start from the time 18.00 of this video. The Consumer C1 finds the condition false, this means the bucket is empty.
As I understand, as long as the condition is false, as I write to the following code, the 3 lines will be skipped, and the C1 will "jump" to the point where the comment "Before leaving the synchronized block" is. After that, the C1 will leave the critical section, and will release the lock (just not doing anything). After that any producer can get the lock and enter in the critical section. I don't understand why you said that the C1 with condition false (on an empty bucket), will check the condition for 5 secs without doing anything? If the condition is false the C1 goes at the end of the if block and the life continues.

while(true){
synchronized(Main.bucket){
if(condition is
// Before leaving the synchronized block
}
}

I hope you understand what i need. Thanks a lot in advance

thomasmylonas
join shbcf.ru