Homework 03 is finalized
peterson-lock.zipclass PetersonLock {
private boolean[] flag = new boolean[2]; private int victim;
public void lock () {
int i = ((PetersonThread)Thread.currentThread())
.getPetersonId();
int j = 1 - i;
flag[i] = true; victim = i;
while ((flag[0] && flag[1]) && victim == i) {};}
public void unlock () {
int i = ((PetersonThread)Thread.currentThread()).getPetersonId();
flag[i] = false;}}

volatile VariablesJava can make variables visible between threads:
volatile keywordvolatile are atomicDrawbacks:
volatile variables are less efficientcount++ not atomicvolatile SomeClass..., only the reference is treated as volatilePetersonLock
flag: an array (object) can’t be volatile
boolean flag0, flag1
victimLockedCounter
countpeteson-lock.zipWhat have we done?
Theory and practice converge!
The Good:
The Bad:
PetersonThread to assign IDsQuestion. How could we lock more simply?
Use more advanced Atomic Objects!
Introducing the AtomicBoolean class:
var ab = new AtomicBoolean(boolean value) make an AtomicBoolean with initial value value
ab.get() return the current valueab.getAndSet(boolean newValue) atomically set the value to newValue and return the old valueab.compareAndSet(boolean expected, boolean new) atomically update to new if previous value was expected and return whether or not the value was updatedQuestion. How could we use AtomicBooleans to design a simpler lock?
Idea. An AtomicBoolean locked stores state of the lock:
locked.get() == true indicates the lock is in uselocked.get() == false indicates the lock is freeObtaining the lock:
locked is false, and set it to true
Releasing the lock:
locked to falseTASLock in Codeimport java.util.concurrent.atomic.AtomicBoolean;
public class TASLock implements SimpleLock {
AtomicBoolean locked = new AtomicBoolean(false);
public void lock () {
while (locked.getAndSet(true)) {}
}
public void unlock () {
locked.set(false);
}
}
tas-locks.zip
Question. Is TASLock deadlock-free? Starvation-free?
Potential Issue:
getAndSet operation is somewhat inefficient
get
Test and Test and Set Lock:
getAndSet
TTASLock Implementationpublic class TTASLock implements SimpleLock {
AtomicBoolean locked = new AtomicBoolean(false);
public void lock () {
while (true) {
while (locked.get()) {};
if (!locked.getAndSet(true)) { return;}
}
}
public void unlock() { locked.set(false);}
}
tas-locks.zip