Nonvolatile variable value during wait () and notifyall () call in 2 threads

Suppose I have two threads A and B, and inside these both threads there is a block synchronized

in which the variable is int

constantly changing. For example, thread A

put in a sync block, change the int variable, then call these 2 methods:

notifyall(); //to wake thread B which is in waiting state and
wait(): 

      

and after that thread B

get the lock and do the same steps as thread A and the process keep repeating. All changes to the int variable happen inside the synchronized block of both threads.

My question is, I need to make an int variable volatile

. Make a thread into main memory before they go into a wait state and reload the data in registers when the thread locks the lock again as a result of the call notifyall();

.

+3


source to share


3 answers


If A and B are running alternatively and not at the same time, and if they are disconnected through calls wait()

and notifyAll()

on the same Object

, and if no other threads are accessing the variable in question, then the variable is mutable.

Note that o.wait()

both o.notifyAll()

must be called within a method or block that is synchronized on o

- this synchronization is sufficient to ensure that the two threads see that all the other's writes are written to any variable before off.



Make sure the two threads sync on the same object, which is not clear from your question. You don't have efficient synchronization at all if, say, two threads are waiting and notifying different instances of the same class.

+5


source


The answer is no , you don't need to make a variable volatile

. The assumption is that writes that occur to a variable in a block synchronized

will be visible to subsequent threads entering a synchronized block on the same object.



Thus, it has the same memory semantics as volatile read and write.

+1


source


Not sure about java. But in C

: https://www.kernel.org/doc/Documentation/volatile-considered-harmful.txt

If shared_data were declared volatile, locking would still be needed. But the compiler will also be prohibited from optimizing access to shared_data in the critical section when we know no one else can work with it. As long as the lock is held, shared_data is not volatile. When dealing with shared data, proper locking makes mutable unnecessary β€” and potentially dangerous.

0


source







All Articles