In what cases is it necessary to synchronize access to instance members? I understand that access to static members of a class always needs to be synchronized- because they
If you want to make this class thread safe I would declare instanceVar
as volatile
to make sure you get always the most updated value from memory and also I would make the setInstanceVar()
synchronized
because in the JVM an increment is not an atomic operation.
private volatile int instanceVar =0;
public synchronized setInstanceVar() { instanceVar++;
}