A
Alan Gutierrez
I'm implementing a log and I have a logging thread that writes log
entires to file. Below is skeletal code to illustrate a question I have
about concurrency and memory.
public class Queued {
public void main(String[] args) {
final LinkedBlockingQueue<List<Integer>> queue =
new LinkedBlockingQueue<List<Integer>>();
Thread thread = new Thread(new Runnable() {
public void run() {
for (; {
try {
List<Integer> list = queue.take();
if (list.get(0) != 0) {
continue;
}
} catch (InterruptedException e) {
continue;
}
}
}
});
thread.start();
List<Integer> list = new ArrayList<Integer>();
list.add(1);
queue.offer(list);
list = new ArrayList<Integer>();
list.add(0);
queue.offer(list);
thread.join();
}
}
As you can see, I'm using a normal list and passing it through a
blocking queue to a thread that pulls a list form the queue and acts on
the first element in the list.
This code appears to me to be broken. The list is not synchronized or
otherwise thread safe, so when the taker thread obtains a reference to
the list, the list may be empty.
It wouldn't be a question if I was using an immutable object, but is
there a good way to ensure that mutable objects are flushed before
sending them off to another thread? (Or does the above code work and I
just don't know it?)
entires to file. Below is skeletal code to illustrate a question I have
about concurrency and memory.
public class Queued {
public void main(String[] args) {
final LinkedBlockingQueue<List<Integer>> queue =
new LinkedBlockingQueue<List<Integer>>();
Thread thread = new Thread(new Runnable() {
public void run() {
for (; {
try {
List<Integer> list = queue.take();
if (list.get(0) != 0) {
continue;
}
} catch (InterruptedException e) {
continue;
}
}
}
});
thread.start();
List<Integer> list = new ArrayList<Integer>();
list.add(1);
queue.offer(list);
list = new ArrayList<Integer>();
list.add(0);
queue.offer(list);
thread.join();
}
}
As you can see, I'm using a normal list and passing it through a
blocking queue to a thread that pulls a list form the queue and acts on
the first element in the list.
This code appears to me to be broken. The list is not synchronized or
otherwise thread safe, so when the taker thread obtains a reference to
the list, the list may be empty.
It wouldn't be a question if I was using an immutable object, but is
there a good way to ensure that mutable objects are flushed before
sending them off to another thread? (Or does the above code work and I
just don't know it?)