Would give me the answers on this problem?

## Discussions

### TSS feedback: Would give me the answers on this problem?

1. #### Would give me the answers on this problem? (2 messages)

This problem is about thread, but I wonder what is currect answers? Is there anyone who give me the right answers?

problem> under which conditions will check() return true when called from a different class?

public class SynchTest{
private int x;
private int y;
private synchronized void setX(int i){x = i;}
private synchronized void setY(int i){y = i;}
public void setXY(int i){ setX(i); setY(i);}

public synchronized boolean check(){
return x!=y;
}
}

a. check() can never return true
b. check() can return true when setXY is called by multiple
c. check() can return true when multiple threads call setX
and setY separately
d. check() can only return true if SynchTest is changed to
allow x and y to be set separately

2. #### Would give me the answers on this problem?[ Go to top ]

It can never return true:

The variables x and y are private and can therefore only be set by methods in the class. The methods that set the variables are also private and can therefore not be called directly from outside the class. Therefore the only way to set x and y is via setXY(int i). If a thread calls setXY() it then calls setX() this method is synchronized this means that no other thread can access this method or any other block that is synchronized on the same object ie 'this'. However the same thread is going to access setY() which it can becuese it still holds the key 'this'.

Basically x and y can only be set by the same thread therefore will always be equal.
3. #### Would give me the answers on this problem?[ Go to top ]

I is not sure that "It can never return true" is the correct answer, because sexXY not is synchronized.

I think setXY is equals to:

public void setXY(int i){
synchronized(this) {x = i;}
synchronized(this) {y = i;}
}

If the WM performs a thread shift when first synchronized is released and before second synchronized is performed we will ha a situation where x and y not contains same value.

I am not familiar with all optimizing ruls. If the compiler or VM optimize this by using only one lock (synchronized) the result will be "It can never return true".