I have the following code:
public class State {
private List<Position> m_track;
public State() {
m_track = Collections.synchronizedList(new ArrayList<Position>());
}
public List<Position> getTrack() {
return m_track;
}
}
// in different class
public void modifyTrack(State _state) {
List<Position> local_track = _state.getTrack();
synchronized (local_track) {
// safely modify track
}
}
But Android Studio gives me a warning on line synchronized (local_track)
:
Synchronization on local variable 'local_track' Reports synchronization on a local variable or parameter.
It is very difficult to guarantee correctness when such synchronization is used.
It may be possible to improve code like this by controlling access through e.g. a synchronized wrapper class, or by synchronizing on a field.
If I replace synchronized (local_track)
with synchronized (_state.getTrack())
warning goes away.
If I understand correctly my local_track
is just a reference and no new object is created and if so why can't I synchronize on it?