Java,
a parere di un mio amico, non permetterebbe di realizzare primitive di
Test-and-Set.
Una
primitiva di Test-and-Set è una primitiva atomica che due o più
threads usano per sincronizzare l'accesso mutualmente esclusivo ad una
risorsa condivisa. Qualsiasi decente libro sui sistemi operativi riporta
definizione, uso, vantaggi e svantaggi di questo design-pattern. Curiosando
in rete Jan Newmarch
scrive:
A
test and set instruction is guaranteed to be indivisible. It reads the
value of a memory location into a register. After that it sets the memory
location to a value. It achieves indivisibility by holding the bus during
the read and successive write so that no other memory operations can be
done.
lock:
if TSL(lock, 1) == 0
lock succeeded
else
lock failed
unlock:
set lock to 0
La
mia proposta di realizzazione di Test-and-Set in Java a questo punto è
stata la seguente:
final
class TestAndSet {
private boolean busy;
TestAndSet(boolean initialBusy){
busy = initialBusy;
}
TestAndSet(){
this(true);
}
synchronized void releaseResource(){
busy = false;
try {notify();} catch (Throwable t) {}
}
synchronized void lockResourceWaiting(){
while (busy)
try {wait();} catch (Throwable t) {}
busy = true;
}
synchronized boolean testAndLockResource(){
if (busy) // already locked
return false; // by another
else {
busy = true;
return true; // locked by me
}
}
}
Quando,
nel settembre del 1999, il mio amico ha analizzato la mia proposta ne ha
riconosciuto la funzionalità (cioè TestAndSet
fa quello che deve fare) ma ne ha anche riscontrato un difetto. Qual'è
il difetto e come si corregge?
La
soluzione, come al solito, fra due mesi su queste pagine.