how does Thread.join works with synchronized/non-synchronized methods

Just before the main method exits, the account’s number field is guaranteed to have value 2000.
A)true
B)false

here, I am confused on following 3 things:
1. in above exact code, both s1 and s2 are showing their values as TERMINATED. yet the account's number value is not guaranteed as 2000. Why is it so?.
2. also when I add synchronized keyword in account's method increase(), then the number value is guaranteed to come as 2000. How?
3. in above case 2 if I comment the join() statements, and let the increase() method be synchronized then again number's value is NOT guaranteed to be 2000. How & Why?

forgive me for quering too many things 1 question, but I am totally confused. I know that's the single object's resource that two objects are using. I also know that join method holds the thread on wait until the thread on which it is called has been completed. So there are 3 threads : one, two and main. But still confused to see output.

Tushar Goel

Ranch Hand

Posts: 934

4

posted 2 years ago

in above exact code, both s1 and s2 are showing their values as TERMINATED. yet the account's number value is not guaranteed as 2000. Why is it so?.

Both threads access increase method randomly but not in serial way when you don't synchronized increase method hence not atomic. That's why you can't guarantee for 2000 value.

also when I add synchronized keyword in account's method increase(), then the number value is guaranteed to come as 2000. How?

After making it synchronized you are making the increase method atomic which guarantees only 1 thread can access at any time. Hence value is 2000.

Tushar Goel

Ranch Hand

Posts: 934

4

posted 2 years ago

in above case 2 if I comment the join() statements, and let the increase() method be synchronized then again number's value is NOT guaranteed to be 2000. How & Why?

in above case 2 if I comment the join() statements, and let the increase() method be synchronized then again number's value is NOT guaranteed to be 2000. How & Why?

I am not sure about this. Lets wait for the masters speak about it.

If the main thread doesn't wait for the other threads to finish (ie. with the join() method call), then it may look at the "result" before the threads finish. Hence, it may not be at the value of 2000 yet.