1

How can you ensure that program threads with common instance access - defined below in Coordinates class, could not read coordinates in an inconsistent state, that is between two commands of the setXY method? Solution in case you can modify the class - coordinates or even if you can't.

public class Coordinates {
 int x, y;
 public int[] getXY() {return new int[]{x, y};}
 public void setXY(int x, int y) {
 this.x = x;
 this.y = y;
 }
}
spammik
  • 163
  • 7

1 Answers1

1
public class Coordinates {
    private int x;
    private int y;
    public synchronized int[] getXY() {return new int[]{x, y};}
    public synchronized void setXY(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

You can modify your code as above.

The field is private, meaning that other classes cannot access or modify this property. When the method is called, a lock on the object instance is obtained. When the method call is finished, the lock is automatically released. This ensures that there is only one thread currently accessing the method.

However, the above code only works for small-scale concurrency - there is a big performance problem. All getters and setters have only single-threaded access. There may be a way to solve your problem in a high concurrency situation, but you will need to make your question clearer.

taylorthurlow
  • 2,953
  • 3
  • 28
  • 42
huanghao
  • 236
  • 2
  • 4