I have a method (example below) which creates a new list, puts some stuff into it, and passes it along to another thread to operate on.
This seems thread safe. The list is local to the method which creates it. The method operates on the list and doesn't pass it to another thread until it is done operating on it.
But this feels wrong, because the list is accessed in two separate threads but it is not synchronized.
Is this acceptable thread-safe code?
class App
{
public static void main(String[] args)
{
final ArrayList<Integer> list = new ArrayList<Integer>();
list.add(4);
list.add(5);
final ExecutorService es = Executors.newSingleThreadExecutor();
es.execute(new Runnable() {
@Override public void run()
{
for (Integer i : list)
System.out.println(i);
}});
es.shutdown();
}
}