Mars
Mars

Reputation: 13

java thread architecture and app design

I have a variable declared as:

private static List<String> _search_result_list = new ArrayList<String>( 15 );

In this app, there are a series of threads that connect to various servers and get data from the URLs supplied to the threads. The threads get the results of the URLs, convert them to text, and store them in _search_result_list. My questions is about synchronizing thread access _search_result_list. What is the best way to go about this?

In addition, the threads are not created in the same class as _search_result_list, and actually don't have access to _search_result_list's enclosing class. Is it sufficient to pass a _search_result_list pointer to the class that creates the threads, and then have that class supply each thread with a pointer to _search_result_list. Will this require synchronization, or does it even matter if the threads attempt to write to the ArrayList simultaneously?

Any input is appreciated.

Mars

Upvotes: 1

Views: 1140

Answers (2)

Peter Knego
Peter Knego

Reputation: 80340

The easiest is to use a synchronized List:

  1. Wrap your List in Collections.synchronizedList(list)

    private static List<String> _search_result_list = 
             Collections.synchronizedList(new ArrayList<String>(15));
    
  2. If you have many more reads than writes than use CopyOnWriteArrayList.

Upvotes: 2

khachik
khachik

Reputation: 28693

public void addData(String data) {
   synchronized(_search_result_list) {
      _search_result_list.add(data);
   }
}

Upvotes: 0

Related Questions