I am using a LinkedList in an android application, where I encounter race conditions. 1 thread adds data to the LinkedList while another removes them when they are retrieved. I encountered the siuation where my newly added objects are never handled.
I Googled for Java synchronized objects, but either I am thinking too easy or I am missing something. From what I’ve read “Object synchronization” is the more difficult of the two, so I was wondering if just enclosing a piece of code with sychronized(object) { }; is enough?
So, I have:
public void function addMove(Object move) {
synchronized(list) {
list.add(move);
};
};
public void function second() {
synchronized(list) {
// iterate through the list
list.clear;
};
};
Is this really all I need?
If the list is properly encapsulated into your object (i.e. no other object has access to the list), and if these are the only methods accessing the list, then yes, this is all you need.
The key is that every access to the list must be done in a synchronized block. And every synchonized block must synchronize on the same object (
list, in your code example).