When I have a common singleton pattern like the one above: To make it thread save, I made the access to adding and removing listeners synchroinized on the list of the listeners. But is it important to do this with every access on every listener? For example, should the same think be done with the setPosition method?
public class Singleton {
private static Singleton instance;
private final List<ChangeListener> listeners = new ArrayList<>();
private int position;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
for (ChangeListener l : listeners) {
l.do(position);
}
}
public void addChangeListener(ChangeListener listener) {
synchronized (listeners) {
listeners.add(listener);
}
}
public void removeChangeListener(ChangeListener listener) {
synchronized (listeners) {
listeners.remove(listener);
}
}
public interface ChangeListener {
public void do(int a);
}
}