I have few ArrayList
containing user defined objects (e.g. List
). The objects are immutable in nature
Yes, you should be able to pass the array into each thread. There should be no access errors so long as the array is finished being written to before any thread is possibly getting the information.
You can share any objects or data structures between threads if they are never modified after a safe publication. As mentioned in the comments, there must be a * happen-before* relationship between the writes that initialize the ArrayList
and the read by which the other threads acquire the reference.
E.g. if you setup the ArrayList
completely before starting the other threads or before submitting the tasks working on the list to an ExecutorService
you are safe.
If the threads are already running you have to use one of the thread safe mechanisms to hand-over the ArrayList
reference to the other threads, e.g. by putting it on a BlockingQueue
.
Even simplest forms like storing the reference into a static final
or volatile
field will work.
Keep in mind that your precondition of never modifying the object afterwards must always hold. It’s recommended to enforce that constraint by wrapping the list using Collections.unmodifiableList(…) and forget about the original list reference before publishing:
class Example {
public static final List<String> THREAD_SAFE_LIST;
static {
ArrayList<String> list=new ArrayList<>();
// do the setup
THREAD_SAFE_LIST=Collections.unmodifiableList(list);
}
}
or
class Example {
public static final List<String> THREAD_SAFE_LIST
=Collections.unmodifiableList(Arrays.asList("foo", "bar"));
}