简体   繁体   中英

Thread scheduling and synchronization

Is it possible for the thread scheduler to unschedule a thread holding the lock to a synchronized block and is in the middle of executing it? If yes then does the unscheduling leads to thread releasing the lock? Assume thread doesn't call method such as wait/yield etc.

I have been trying to understand how synchronized block helps in read-update-write operation? If the thread which enters the synchronized block can't be unscheduled then it's easier to understand but if it can be then the issue of visibility comes as it might be the case that variable has been updated but not written to the main memory by thread and thread scheduler unschedules it and other thread gets the lock and updated the variable in the main memory. Is there any info. in JLS regarding the same?

Is it possible for the thread scheduler to unschedule a thread holding [a lock]?

Yes, that can happen preemptively in many scheduling algorithms . It must happen if the thread makes a blocking system call (eg, to wait for input).

If yes then does the unscheduling leads to thread releasing the lock?

Absolutely not! That would defeat the purpose of locking, and it would break most multi-threaded programs.


Takeaway: Keep your critical sections as short as possible! Don't let threads B, C, D, and E all get blocked waiting for thread A to release some lock when thread A is blocked performing a long computation (or worse, waiting for input).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM