MX Java Solutions
MX Java Solutions
Solutions
F29OC
ss002.00_2020_01_09_Threads_intro
Recall Basic Race Problem
Multiple Threads
(or processes)
i++
Time
i++
Multiple Threads
(or processes)
i++
i++
http://tutorials.jenkov.com/java-concurrency/ja
va-memory-model.html
lock
unlock
lock
unlock
lock
unlock
From <https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicBoolean.html#compareAndSet(boolean,%20boolean)>
• compareAndSet()
Easier programming of
providing Critical Regions
From <https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicBoolean.html#compareAndSet(boolean,%20boolean)>
void criticalRegion() {
while (!atomicBoolean.compareAndSet(false, true) {
}
// CR code here
Occupied
Apr 21, 2024 19
Thread States in Busy Wait
• Always Runnable – in either ReadyToRun or
Running (on a CPU)
Runnable
Ready to
Run
Running
Ready to
Run
Running
Thread.sleep
Timed_ (duration)
waiting
v.getAndSet(arg)
• sets variable v to arg
• returns the value of v before update
• Java • Tanenbaum
.acquire( ) = down(&semaphore)
.release( ) = up(&semaphore)
Permit is “transferred”
back to Semaphore
Ready to
Run
Running
sem.acquire() on
semaphore with no
permits blocks
calling thread on the
Waiting Waiting Q
Runnable
Ready to
Run
Running
sem.release()
Waiting
Implementation for multiple semaphores likely to
use multiple Wait Queues
Runnable
TCB TCB
Ready to
Run
registers registers
head
Runnable Q
. .
tail .
.
.
.
Running
TCB TCB
registers registers
head . .
Waiting Q . .
sem.release() tail . .
TCB
registers
head .
Waiting Q tail
.
.
Waiting TCB
TCB TCB
registers
registers registers
.
.
head . .
Waiting Q tail
.
.
.
.
.
//In Thread
sem.acquire();
• A thread can only execute a synchronised method if it owns the objects monitor.
• If another thread already owns the object’s monitor then the new caller will ne blocked from
proceeding.
Read: https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html
Apr 21, 2024 43
Intrinsic Monitors
Thread tries to acquire control
(ownership) of monitor
(Thread will be blocked
from proceeding if another
thread already has control)