Elliott
Elliott

Reputation: 5609

Large Object Arrays shared among multiple threads. Thread Safe Techniques

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:

  1. The objects values are initialized prior to threading.
  2. The objects are shared (read only) by multiple threads.
  3. When an object needs to be modified, a copy of the object is made and changes are made to the copy.

Here are my questions.

  1. Do getters and setters for variable1 and variable2 need to be synchronized. Since I am only reading the objects when shared between threads, this seems unnecessarily but please correct me if I am wrong.
  2. Is there a better way to share a large arraylist of information. (I don't want to copy the arraylist for each thread because it is huge with greater than 200K objects)?

Upvotes: 2

Views: 875

Answers (2)

Peter Lawrey
Peter Lawrey

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

giorashc
giorashc

Reputation: 13713

  1. If you make a copy of the objects stored in your read-only shared array than there is no need to synchornize getters/setters.

  2. Your approach seems to be fine as long as the list is read only

Upvotes: 5

Related Questions