From 906e58ef7cad4f0fcc08c41e7223c942679ce69d Mon Sep 17 00:00:00 2001 From: xiangflight Date: Thu, 12 Jul 2018 14:51:39 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86=E9=83=A8=E5=88=86Co?= =?UTF-8?q?pyOnWriteArrayList=E7=9A=84=E7=AE=80=E4=BB=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .DS_Store | Bin 0 -> 6148 bytes notes/Java 容器.md | 25 +++++++++++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..b36190334234c2eda81663fa9356d3044da733a1 GIT binary patch literal 6148 zcmeHK&1(}u6n|5r?lyjGYpbm&EaqUrB9&G>h`7d9Eh?!=tc}&iO?H|tZfC;ornQzr z5WEUr6~Tiac=8VrJg5i%1TW&BpcfCG^vy?TO!X=v`@+oc<<0NC-T5uEvjYGm+whJ6 zSO8#P6PW78?l&gJMcZIqIwA&%tZ@-0p#ViV42v7sNgz=mQQ%)wK&;&~WFd#Y3(&rP zy~%)AD*>+{L%beNU>o`&4LyL(z<@&x6rv91%Re(K%TZm|{8p(4eiV<4d?a0)Qk%DI zHO%g`nck5$Zxj~zav^r(MwE5KvbC?^d$i()SA8#DC{i{N&?U-p;YBy5;jADRIS-Ja ze77>~)8(?&cZRdr^%)IiJyqlSRiAl$Im;W&izHtcm;RI+FJK)b$qOtqt3&$B&N;+he20*49kJ7(943Ki9Z>|KX#j&z`?{`%Y#7!PlX*9*r${ zk4~F#esxL9LEg0F_-t8if^6HqW2e>AyQ`=TMx)`=R!)Ete2agk7zto zwsuC;EoVqM7G#tIka1QV=^GX)GR~-J zW}GQKYQP~l4VPdVZowUR0FU7nyoL|(3BJI0vXu;y1LP1HBPYoza-Li!c~T@La*fQY z{I1q>-LLCuARanx&vmH~vVgN1Mny&n>fl4QbD@wuIM%+TOvu9o-rqRh;e^~oI~F0i z*OAeU+wB!(U&5?Blzx{Z7w+@6g^MMW>B$)BRv^Jdfkc5s0j+>|KiJp=IvSe_<*Nfb zc?3XAVOSda;$uPN*cu&;O@%muMpP=IN+tS;K~y@%ZOwBuHWjLLAo}n@^p%M|p%8g> ztZz#?5JzFsCkiAA{Hnkv_16;n|HPlq|Gy?B{}Kff1^z1qNNT(=p2aEYy>-Ln#9nJ- uyNOMh;58M>6zueNEFG~G4`7pqW43S*9gR(e7(q)u1f&c}mniU875E7(>Kowz literal 0 HcmV?d00001 diff --git a/notes/Java 容器.md b/notes/Java 容器.md index 55cffe2c..bdb97bb5 100644 --- a/notes/Java 容器.md +++ b/notes/Java 容器.md @@ -255,6 +255,31 @@ List synList = Collections.synchronizedList(list); List list = new CopyOnWriteArrayList<>(); ``` +扩展:CopyOnWriteArrayList是一种CopyOnWrite容器,即写时复制的容器。从以下源码中看出:当向容器中添加元素时,不是直接往当前容器添加,而是Copy当前容器,在新容器中添加,添加完后,将原容器的引用指向新容器。这样做可以对CopyOnWrite容器进行并发的读,不需要加锁,极大地提高了读性能,因此适用于读多写少的场景。 + +```java +public boolean add(E e) { + final ReentrantLock lock = this.lock; + lock.lock(); + try { + Object[] elements = getArray(); + int len = elements.length; + Object[] newElements = Arrays.copyOf(elements, len + 1); // 复制到新容器 + newElements[len] = e; + setArray(newElements); + return true; + } finally { + lock.unlock(); + } +} + +@SuppressWarnings("unchecked") +private E get(Object[] a, int index) { + return (E) a[index]; +} + +``` + ## LinkedList ### 1. 概览