java juc 集合_Java多线程系列--“JUC集合”02之 CopyOnWriteArrayList

1 /*

2 * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.3 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.4 *5 *6 *7 *8 *9 *10 *11 *12 *13 *14 *15 *16 *17 *18 *19 *20 *21 *22 *23 *24 */

25

26 /*

27 * Written by Doug Lea with assistance from members of JCP JSR-16628 * Expert Group. Adapted and released, under explicit permission,29 * from JDK ArrayList.java which carries the following copyright:30 *31 * Copyright 1997 by Sun Microsystems, Inc.,32 * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.33 * All rights reserved.34 */

35

36 packagejava.util.concurrent;37 import java.util.*;38 import java.util.concurrent.locks.*;39 importsun.misc.Unsafe;40

41 /**

42 * A thread-safe variant of {@linkjava.util.ArrayList} in which all mutative43 * operations (add, set, and so on) are implemented by44 * making a fresh copy of the underlying array.45 *46 *

This is ordinarily too costly, but may be more efficient47 * than alternatives when traversal operations vastly outnumber48 * mutations, and is useful when you cannot or don't want to49 * synchronize traversals, yet need to preclude interference among50 * concurrent threads. The "snapshot" style iterator method uses a51 * reference to the state of the array at the point that the iterator52 * was created. This array never changes during the lifetime of the53 * iterator, so interference is impossible and the iterator is54 * guaranteed not to throw ConcurrentModificationException.55 * The iterator will not reflect additions, removals, or changes to56 * the list since the iterator was created. Element-changing57 * operations on iterators themselves (remove, set, and58 * add) are not supported. These methods throw59 * UnsupportedOperationException.60 *61 *

All elements are permitted, including null.62 *63 *

Memory consistency effects: As with other concurrent64 * collections, actions in a thread prior to placing an object into a65 * {@codeCopyOnWriteArrayList}66 * happen-before67 * actions subsequent to the access or removal of that element from68 * the {@codeCopyOnWriteArrayList} in another thread.69 *70 *

This class is a member of the71 * 72 * Java Collections Framework.73 *74 *@since1.575 *@authorDoug Lea76 *@param the type of elements held in this collection77 */

78 public class CopyOnWriteArrayList

79 implements List, RandomAccess, Cloneable, java.io.Serializable {80 private static final long serialVersionUID = 8673264195747942595L;81

82 /**The lock protecting all mutators*/

83 transient final ReentrantLock lock = newReentrantLock();84

85 /**The array, accessed only via getArray/setArray.*/

86 private volatile transientObject[] array;87

88 /**

89 * Gets the array. Non-private so as to also be accessible90 * from CopyOnWriteArraySet class.91 */

92 finalObject[] getArray() {93 returnarray;94 }95

96 /**

97 * Sets the array.98 */

99 final voidsetArray(Object[] a) {100 array =a;101 }102

103 /**

104 * Creates an empty list.105 */

106 publicCopyOnWriteArrayList() {107 setArray(new Object[0]);108 }109

110 /**

111 * Creates a list containing the elements of the specified112 * collection, in the order they are returned by the collection's113 * iterator.114 *115 *@paramc the collection of initially held elements116 *@throwsNullPointerException if the specified collection is null117 */

118 public CopyOnWriteArrayList(Collection extends E>c) {119 Object[] elements =c.toArray();120 //c.toArray might (incorrectly) not return Object[] (see 6260652)

121 if (elements.getClass() != Object[].class)122 elements = Arrays.copyOf(elements, elements.length, Object[].class);123 setArray(elements);124 }125

126 /**

127 * Creates a list holding a copy of the given array.128 *129 *@paramtoCopyIn the array (a copy of this array is used as the130 * internal array)131 *@throwsNullPointerException if the specified array is null132 */

133 publicCopyOnWriteArrayList(E[] toCopyIn) {134 setArray(Arrays.copyOf(toCopyIn, toCopyIn.length, Object[].class));135 }136

137 /**

138 * Returns the number of elements in this list.139 *140 *@returnthe number of elements in this list141 */

142 public intsize() {143 returngetArray().length;144 }145

146 /**

147 * Returns true if this list contains no elements.148 *149 *@returntrue if this list contains no elements150 */

151 public booleanisEmpty() {152 return size() == 0;153 }154

155 /**

156 * Test for equality, coping with nulls.157 */

158 private static booleaneq(Object o1, Object o2) {159 return (o1 == null ? o2 == null: o1.equals(o2));160 }161

162 /**

163 * static version of indexOf, to allow repeated calls without164 * needing to re-acquire array each time.165 *@paramo element to search for166 *@paramelements the array167 *@paramindex first index to search168 *@paramfence one past last index to search169 *@returnindex of element, or -1 if absent170 */

171 private static intindexOf(Object o, Object[] elements,172 int index, intfence) {173 if (o == null) {174 for (int i = index; i < fence; i++)175 if (elements[i] == null)176 returni;177 } else{178 for (int i = index; i < fence; i++)179 if(o.equals(elements[i]))180 returni;181 }182 return -1;183 }184

185 /**

186 * static version of lastIndexOf.187 *@paramo element to search for188 *@paramelements the array189 *@paramindex first index to search190 *@returnindex of element, or -1 if absent191 */

192 private static int lastIndexOf(Object o, Object[] elements, intindex) {193 if (o == null) {194 for (int i = index; i >= 0; i--)195 if (elements[i] == null)196 returni;197 } else{198 for (int i = index; i >= 0; i--)199 if(o.equals(elements[i]))200 returni;201 }202 return -1;203 }204

205 /**

206 * Returns true if this list contains the specified element.207 * More formally, returns true if and only if this list contains208 * at least one element e such that209 * (o==null ? e==null : o.equals(e)).210 *211 *@paramo element whose presence in this list is to be tested212 *@returntrue if this list contains the specified element213 */

214 public booleancontains(Object o) {215 Object[] elements =getArray();216 return indexOf(o, elements, 0, elements.length) >= 0;217 }218

219 /**

220 * {@inheritDoc}221 */

222 public intindexOf(Object o) {223 Object[] elements =getArray();224 return indexOf(o, elements, 0, elements.length);225 }226

227 /**

228 * Returns the index of the first occurrence of the specified element in229 * this list, searching forwards from index, or returns -1 if230 * the element is not found.231 * More formally, returns the lowest index i such that232 * (i >= index && (e==null ? get(i)==null : e.equals(get(i)))),233 * or -1 if there is no such index.234 *235 *@parame element to search for236 *@paramindex index to start searching from237 *@returnthe index of the first occurrence of the element in238 * this list at position index or later in the list;239 * -1 if the element is not found.240 *@throwsIndexOutOfBoundsException if the specified index is negative241 */

242 public int indexOf(E e, intindex) {243 Object[] elements =getArray();244 returnindexOf(e, elements, index, elements.length);245 }246

247 /**

248 * {@inheritDoc}249 */

250 public intlastIndexOf(Object o) {251 Object[] elements =getArray();252 return lastIndexOf(o, elements, elements.length - 1);253 }254

255 /**

256 * Returns the index of the last occurrence of the specified element in257 * this list, searching backwards from index, or returns -1 if258 * the element is not found.259

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值