Java collections are by default not synchronized. There is a big notice in the ArrayList
documentation (the bold text in the class description) to that effect. Fortunately for you, there is also a method Collections.synchronizedList()
that returns a wrapper for your ArrayList
, or any other List
that will be synchronized properly so you do not have to do it yourself.
As far as accessing the shared wrapper object, you can either pass a reference to your thread or have a class with static or singleton (global) access to the objects you are sharing. The second option is probably better if you have may shared objects.
If you want to read and write to a file, you can use the RandomAccessFile
class. Here, synchronization will be trickier because the class is not thread safe. You may want to put synchronization into your static/singleton class that has the array list. Here is a thread on synchronizing file access: Java: thread-safe RandomAccessFile.
For your purposes, it may be easier to use a logger. This is an object that is inherently synchronized. A basic logging API is provided by the java.util.logging package
. Here is a good tutorial on logging: http://www.vogella.com/articles/Logging/article.html