This homework has two types of problems:
Self Check: You are strongly encouraged to think about and work through these questions, but you will not submit answers to them.
Problems: You will turn in answers to these questions.
Read Mitchell, Chapter 14.1 -- 14.2, 14.4 (up through page 461)
Scala Actors Tutorials, as needed. (A good starting point is http://www.scala-lang.org/node/242).
The DoubleCounter class defined below has methods incrementBoth
and getDifference. Assume that DoubleCounter will be used in
multi-threaded applications.
class DoubleCounter {
protected int x = 0;
protected int y = 0;
public int getDifference() {
return x - y;
}
public void incrementBoth() {
x++;
y++;
}
}
There is a potential data race between incrementBoth and
getDifference if getDifference is called between the increment
of x and the increment of y. You may assume that x++ and y++
execute atomically (although this is not always guaranteed...).
What are the possible return values of getDifference if there
are two threads that each invoke incrementBoth exactly once at
the same times as a third thread invokes getDifference?
What are the possible return values of getDifference if there
are n threads that each invoke incrementBoth exactly once?
Data races can be prevented by inserting synchronization primitives. One option is to declare
public synchronized int getDifference() {...}
public int incrementBoth() {...}
This will prevent two threads from executing method
getDifference at the same time. Is this enough to ensure that
getDifference always returns 0? Explain briefly.
Is the following declaration
public int getDifference() {...}
public synchronized int incrementBoth() {...}
sufficient to ensure that getDifference always returns 0?
Explain briefly.
What are the possible values of getDifference if the following
declarations are used?
public synchronized int getDifference() {...}
public synchronized int incrementBoth() {...}
Submit your answers to the GradeScope assignment named, for example, "HW 0". It should:
You will be asked to resubmit homework not satisfying these requirements. Please select the pages for each question when you submit.