Reputation: 5609
I have a large ArrayList of objects similar to the following
class Entry {
private String variable1 = null;
private int variable2 = 0;
public Entry (String variable1) {
this.variable1 = variable1;
}
/* getters and setters for variable1 and 2 are below */
}
I initiate the objects in the ArrayList, then create multiple threads. Each thread searches a large set of documents to determine if the contents of variable1 is embedded in the document. If it is, I want to make a copy of the Entry, specific to the thread, similar to below:
public Entry(Entry entry) {
this(entry.getVariable1())
}
I then want to alter the contents of variable2 of the Copy not the original. To summarize:
Here are my questions.
Upvotes: 2
Views: 875
Reputation: 533530
I would have a collection which shadows the original list with a local copy for each thread.
public class ShadowList<T> {
private final List<T> original;
private final List<T> local;
public ShadowList(List<T> original) {
this.original = original;
local = Arrays.<T>asList((T[]) new Object[original.size()]);
}
public T get(int n) {
T t = local.get(n);
if (t == null)
t = original.get(n);
return t;
}
public void set(int n, T t) {
local.set(n, t);
}
}
Upvotes: 1
Reputation: 13713
If you make a copy of the objects stored in your read-only shared array than there is no need to synchornize getters/setters.
Your approach seems to be fine as long as the list is read only
Upvotes: 5