Tuesday, 15 April 2014

java - Non-volatile variable value during wait() and notifyall() call in 2 threads -



java - Non-volatile variable value during wait() and notifyall() call in 2 threads -

lets have 2 threads , b , within these both 2 threads have synchronized block in int variable modified continously. example, thread a come in synchronized block modify int variable phone call these 2 methods:

notifyall(); //to wake thread b in waiting state , wait():

and after thread b acquire lock , same steps thread , process maintain on repeating. changes int variable happens within synchronized block of both threads.

my question need create int variable volatile. thread flush main memory before go waiting state , reload info in registers when thread acquire lock 1 time again result of notifyall(); call.

if , b run alternatively rather concurrently, , if switch off via wait() , notifyall() invocations on same object, , if no other threads access variable in question, thread safety not require variable volatile.

note o.wait() , o.notifyall() must invoked within method or block synchronized on o -- synchronization sufficient ensure 2 threads see each others' writes variable before switch-off.

do careful ensure 2 threads synchronizing on same object, not clear question. have no effective synchronization @ if, say, 2 threads waiting on , notifying different instances of same class.

java multithreading synchronized volatile

No comments:

Post a Comment