Here is a classic problem given a piece of legacy code written without any threading consideration. How do we make it thread-safe?
The following class illustrates this problem:
private class LegacyCode {
int x;
int y;
public LegacyCode(int x, int y) {
this.x = x;
this.y = y;
}
// setters and getters are skipped
// they are there though
There are two methods, m1() and m2(), which change the instance state in some way. Here is the m1() method:
public void m1() {
setX(9);
setY(0);
}
It sets the x field to 9 and the y field to 0:
public void m2() {
setY(0);
setX(9);
}
The m2() method does the opposite: it sets x to 0 and y to 9.
If we try to make this class concurrent, using threads, you know we need to carefully synchronize access to all shared states. Of course, any legacy code has many other ramifications...