Note that there are some explanatory texts on larger screens.

plurals
  1. POBest way to tranverse List in Java?
    primarykey
    data
    text
    <p>I have a concurrent List used in multi-threaded environment. Once the List is built, mostly operation is traversing it. I am wondering which of the following 2 methods are more efficient, or what's cost of creating a new List vs using synchronized? Or maybe there are other better ways?</p> <pre><code>List&lt;Object&gt; list = new CopyOnWriteArrayList&lt;Object&gt;(); public int[] getAllValue1() { List&lt;Object&gt; list2 = new ArrayList&lt;Object&gt;(list); int[] data = new int[list2.size()]; int i = 0; for (Object obj : list2) { data[i++] = obj.getValue(); } return data; } public int[] getAllValue2() { synchronized (list) { int[] data = new int[list.size()]; int i = 0; for (Object obj : list) { data[i++] = obj.getValue(); } return data; } } </code></pre> <p><strong>UPDATE</strong> getAllValue1(): It is threadsafe, because it takes a snapshot of the CopyOnWriteList, which itself is threadsafe List. However, as sharakan points out, the cost is iterate 2 lists, and creating a local object ArrayList, which could be costly if the original list is large.</p> <p>getAllValue2(): It is also threadsafe in the synchronization block. (Assume other functions do synchronization properly.) The reason to put it in the synchronization block is because I want to pre-allocate the array, to make sure .size() call is synchronized with iteration. (Iteration part is threadsafe, because it use CopyOnWriteList.) However the cost here is the opportunity cost of using syncrhonized block. If there are 1 million clients calling getAllValue2(), each one has to wait.</p> <p>So I guess the answer really depends on how many concurrent users need to read the data. If not many concurrent users, probably the method2 is better. Otherwise, method1 is better. Agree?</p> <p>In my usage, I have a couple concurrent clients, probably method2 is preferred. (BTW, my list is about 10k size).</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload