Name: _____________________________ 6 Digit StudentID: ___ ___ ___ ___ ___ ___

Worksheet 18: Mutual Exclusion

1 Given the partial definition of MutableInt and parallel program below:

public class MutableInt {
    private int value;
    public MutableInt() {
        value = 0;
    }
    public void add(int operand) {
        value += operand;
    }
    public int intValue() {
        return value;
    }
}
MutableInt total = new MutableInt();
Future<Void> f = void_fork(() -> {
    synchronized(total) {
        total.add(11);
    }
});
total.add(10);
join(f);
System.out.println(total.intValue());

1a) Is there a data race? _______

1b) If so, encircle all of the lines which contribute to the data race.

public class MutableText {
    private String text = "";
    public void add(char letter) {
        text += letter;
    }
    public String toSorted() {
        char[] letters = text.toCharArray();
        Arrays.sort(letters);
        return new String(letters);
    }
}
MutableText mutableText = new MutableText();
Future<Void> aFuture = void_fork(() -> {
    synchronized (mutableText) {
        mutableText.add('A');
    }
});
Future<Void> bFuture = void_fork(() -> {
    synchronized (mutableText) {
        mutableText.add('B');
    }
});
Future<Void> cFuture = void_fork(() -> {
    mutableText.add('C');
});
join(aFuture, bFuture, cFuture);
System.out.println(mutableText.toSorted());

2a) Is there a data race? _______

2b) What can run in parallel with:

mutableText.add('A')? __________________
mutableText.add('B')? __________________
mutableText.add('C')? __________________

2c) How many different ways can the reads and writes play out?

2d) What are all the different String lengths when printed?

2e) What are all the different String values when printed?

Post Lecture

Synthesize today's class session

 

 

What is unclear?