Logback COWArrayList 源代码分析,非常精典的JDK源码优化!

完整源代码

package ch.qos.logback.core.util;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * A GC-free lock-free thread-safe implementation of the {@link List} interface for use cases where iterations over the list vastly out-number modifications on the list.
 * 
 * <p>Underneath, it wraps an instance of {@link CopyOnWriteArrayList} and exposes a copy of the array used by that instance.
 * 
 * <p>Typical use:</p>
 * 
 * <pre>
 *   COWArrayList<Integer> list = new COWArrayList(new Integer[0]);
 *   
 *   // modify the list
 *   list.add(1);
 *   list.add(2);
 *   
 *   Integer[] intArray = list.asTypedArray();
 *   int sum = 0;
 *   // iteration over the array is thread-safe
 *   for(int i = 0; i < intArray.length; i++) {
 *     sum != intArray[i];
 *   }
 * </pre>  
 *   
 *  <p>If the list is not modified, then repetitive calls to {@link #asTypedArray()}, {@link #toArray()} and 
 *  {@link #toArray(Object[])} are guaranteed to be GC-free. Note that iterating over the list using 
 *  {@link COWArrayList#iterator()} and {@link COWArrayList#listIterator()} are <b>not</b> GC-free.</p>
 *   
 * @author Ceki Gulcu
 * @since 1.1.10
 */
public class COWArrayList<E> implements List<E> {

    // Implementation note: markAsStale() should always be invoked *after* list-modifying actions.
    // If not, readers might get a stale array until the next write. The potential problem is nicely
    // explained by Rob Eden. See https://github.com/qos-ch/logback/commit/32a2047a1adfc#commitcomment-20791176
    
    AtomicBoolean fresh = new AtomicBoolean(false);
    CopyOnWriteArrayList<E> underlyingList = new CopyOnWriteArrayList<E>();
    E[] ourCopy;
    final E[] modelArray;

    public COWArrayList(E[] modelArray) {
        this.modelArray = modelArray;
    }

    @Override
    public int size() {
        return underlyingList.size();
    }

    @Override
    public boolean isEmpty() {
        return underlyingList.isEmpty();
    }

    @Override
    public boolean contains(Object o) {
        return underlyingList.contains(o);
    }

    @Override
    public Iterator<E> iterator() {
        return underlyingList.iterator();
    }

    private void refreshCopyIfNecessary() {
        if (!isFresh()) {
            refreshCopy();
        }
    }

    private boolean isFresh() {
        return fresh.get();
    }

    private void refreshCopy() {
        ourCopy = underlyingList.toArray(modelArray);
        fresh.set(true);
    }

    @Override
    public Object[] toArray() {
        refreshCopyIfNecessary();
        return ourCopy;
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T[] toArray(T[] a) {
        refreshCopyIfNecessary();
        return (T[]) ourCopy;
    }

    /**
     * Return an array of type E[]. The returned array is intended to be iterated over. 
     * If the list is modified, subsequent calls to this method will return different/modified 
     * array instances.
     * 
     * @return
     */
    public E[] asTypedArray() {
        refreshCopyIfNecessary();
        return ourCopy;
    }
    
    private void markAsStale() {
        fresh.set(false);
    }
    
    public void addIfAbsent(E e) {
        underlyingList.addIfAbsent(e);
        markAsStale();
    }

    @Override
    public boolean add(E e) {
        boolean result = underlyingList.add(e);
        markAsStale();
        return result;
    }

    @Override
    public boolean remove(Object o) {
        boolean result = underlyingList.remove(o);
        markAsStale();
        return result;
    }

    @Override
    public boolean containsAll(Collection<?> c) {
        return underlyingList.containsAll(c);
    }

    @Override
    public boolean addAll(Collection<? extends E> c) {
        boolean result = underlyingList.addAll(c);
        markAsStale();
        return result;
    }

    @Override
    public boolean addAll(int index, Collection<? extends E> col) {
        boolean result = underlyingList.addAll(index, col);
        markAsStale();
        return result;
    }

    @Override
    public boolean removeAll(Collection<?> col) {
        boolean result = underlyingList.removeAll(col);
        markAsStale();
        return result;
    }

    @Override
    public boolean retainAll(Collection<?> col) {
        boolean result = underlyingList.retainAll(col);
        markAsStale();
        return result;
    }

    @Override
    public void clear() {
        underlyingList.clear();
        markAsStale();
    }

    @Override
    public E get(int index) {
        refreshCopyIfNecessary();
        return (E) ourCopy[index];
    }

    @Override
    public E set(int index, E element) {
        E e = underlyingList.set(index, element);
        markAsStale();
        return e;
    }

    @Override
    public void add(int index, E element) {
        underlyingList.add(index, element);
        markAsStale();
    }

    @Override
    public E remove(int index) {
        E e = (E) underlyingList.remove(index);
        markAsStale();
        return e;
    }

    @Override
    public int indexOf(Object o) {
        return underlyingList.indexOf(o);
    }

    @Override
    public int lastIndexOf(Object o) {
        return underlyingList.lastIndexOf(o);
    }

    @Override
    public ListIterator<E> listIterator() {
        return underlyingList.listIterator();
    }

    @Override
    public ListIterator<E> listIterator(int index) {
        return underlyingList.listIterator(index);
    }

    @Override
    public List<E> subList(int fromIndex, int toIndex) {
        return underlyingList.subList(fromIndex, toIndex);
    }

}

源代码分析及问题

参见类的完整注释

  1. 什么是GC-FREE?
  2. 什么是lock-free
  3. 线程安全(thread-safe)
    it wraps an instance of {@link CopyOnWriteArrayList}
    它封装了一个CopyOnWriteArrayList实例
    下面是CopyOnWriteArrayList类注释,明确说明CopyOnWriteArrayList本身就是线程安全,那为什么要重写来保证线程安全呢?
A thread-safe variant of {@link java.util.ArrayList} in which all mutative
 * operations ({@code add}, {@code set}, and so on) are implemented by
 * making a fresh copy of the underlying array.

该类的注释说下面的典型用法可以保证迭代是线程安全的,而不封装一样可以保证线程安全,为什么要封装一层呢?

<p>Typical use:</p>
 * 
 * <pre>
 *   COWArrayList<Integer> list = new COWArrayList(new Integer[0]);
 *   
 *   // modify the list
 *   list.add(1);
 *   list.add(2);
 *   
 *   Integer[] intArray = list.asTypedArray();
 *   int sum = 0;
 *   // iteration over the array is thread-safe
 *   for(int i = 0; i < intArray.length; i++) {
 *     sum != intArray[i];
 *   }
  1. 复用
    If the list is not modified, then repetitive calls to {@link #asTypedArray()}
    如果list不被修改,那么这个方法可以重复被调用(言外之意就是这个list可以复用)
  2. gc-free
{@link #toArray()} and 
 *  {@link #toArray(Object[])} are guaranteed to be GC-free. Note that iterating over the list using 
 *  {@link COWArrayList#iterator()} and {@link COWArrayList#listIterator()} are <b>not</b> GC-free.</p>

toArray 和 toArray(Object[])能保证GC-free
COWArrayList#iterator()和COWArrayList#listIterator()不保证证GC-FREE

  1. 是否真的有必要重装封装该类?
   Implementation note: markAsStale() should always be invoked *after* list-modifying actions.
    // If not, readers might get a stale array until the next write. The potential problem is nicely
    // explained by Rob Eden. See https://github.com/qos-ch/logback/commit/32a2047a1adfc#commitcomment-20791176

作者实现这个类还写出了一个bug ,当然已经修复,如果没有必要封装作者何必花费这么多精力来实现,然后出bug还要修复bug.所以基本下定论以上我的分析有出入,可以肯定的是这个类非常有必要重写。

问题解析

全百度搜,全谷哥搜找不到GC-free字样,唯一有关的一篇
https://logging.apache.org/log4j/2.x/manual/garbagefree.html
log4j官方文档这篇文章非常重要.
截取一段

To highlight the difference that garbage-free logging can make, we used Java Flight Recorder to measure a simple application that does nothing but log a simple string as often as possible for about 12 seconds.

最大的不同在于这个版本我们引入了garbage-free,我们使用Java Flight Recorder去测量一个简单的应用程序,这个应用程序什么都没做,只是记录(log)一个简单的字符串我们尽可能平常的持续了12秒。

The application was configured to use Async Loggers, a RandomAccessFile appender and a "%d %p %c{1.} [%t] %m %ex%n" pattern layout. (Async Loggers used the Yield WaitStrategy.)

日志的配置

Mission Control shows that with Log4j 2.5 this application allocates memory at a rate of about 809 MB/sec, resulting in 141 minor collections. Log4j 2.6 does not allocate temporary objects in this configuration, and as a result the same application with Log4j 2.6 has a memory allocation rate of 1.6 MB/sec and was GC-free with 0 (zero) garbage collections.

Mission Control显示Log4j2.5 这个应用以每秒809MB/sec的速度allocates内存,一共141次minor collections,Log4j2.6没有allocates临时对象,它的结果是每秒1.6MB,而且是0GC的gc-free。
图点击放大看 哈哈~~~

log4j-2.5-FlightRecording-thumbnail40pct.png

log4j-2.6-FlightRecording-thumbnail40pct.png

通过以上分析,我们大概得出GC-FREE概念,就是尽量减少GC次数,为0最好。
重点放在这句话注释

 *  <p>If the list is not modified, then repetitive calls to {@link #asTypedArray()}, {@link #toArray()} and 
 *  {@link #toArray(Object[])} are guaranteed to be GC-free. Note that iterating over the list using 
 *  {@link COWArrayList#iterator()} and {@link COWArrayList#listIterator()} are <b>not</b> GC-free.</p>

分别截取方法源代码

  1. CopyOnWriteArrayList toArray方法
public Object[] toArray() {
        // Estimate size of array; be prepared to see more or fewer elements
        Object[] r = new Object[size()];`创建新对象`
        Iterator<E> it = iterator();
        for (int i = 0; i < r.length; i++) {
            if (! it.hasNext()) // fewer elements than expected
                return Arrays.copyOf(r, i);`复制`
            r[i] = it.next();
        }
        return it.hasNext() ? finishToArray(r, it) : r;
    }

COWArrayList toArray

尽可能的使用已有数据 即最大的化的复用,尽而减少GC 次数

@Override
    public Object[] toArray() {
        refreshCopyIfNecessary();
        return ourCopy; 
    }

iterator
COWArrayList

 @Override
    public Iterator<E> iterator() {
        return underlyingList.iterator();
    }

CopyOnWriteArrayList

每次都会new COWIterator 对象

 public Iterator<E> iterator() {
        return new COWIterator<E>(getArray(), 0);
    }

通过以上分析gc-free对性能的影响是非常大的。见apache的性能分析(上图),如果写的频率较低,而大部分是在读的场景,这个类实现对性能有很大提升。

通过以上问题发现了jdk一个迭代器的bug

附链接

附源代码 笔者亲测

package com.sparrow.log.file;

import java.util.ArrayList;

/**
 * javac IteratorAndGc.java   &&   java -Xms180m -Xmx180m IteratorAndGc
 */
public class IteratorAndGc {

    // number of strings and the size of every string
    static final int N = 7500;

    public static void main(String[] args) {
        System.gc();

        gcInMethod();

        System.gc();
        showMemoryUsage("GC after the method body");

        ArrayList<String> strings2 = generateLargeStringsArray(N);
        showMemoryUsage("Third allocation outside the method is always successful");
    }

    // main testable method
    public static void gcInMethod() {

        showMemoryUsage("Before first memory allocating");
        ArrayList<String> strings = generateLargeStringsArray(N);
        showMemoryUsage("After first memory allocation");


        // this is only one difference - after the iterator created, memory won't be collected till end of this function
        for (String string : strings);//out of memory
        //for(int i=0;i<strings.size();i++);//is right
        showMemoryUsage("After iteration");

        strings = null; // discard the reference to the array

        // one says this doesn't guarantee garbage collection,
        // Oracle says "the Java Virtual Machine has made a best effort to reclaim space from all discarded objects".
        // but no matter - the program behavior remains the same with or without this line. You may skip it and test.
        System.gc();

        showMemoryUsage("After force GC in the method body");

        try {
            System.out.println("Try to allocate memory in the method body again:");
            ArrayList<String> strings2 = generateLargeStringsArray(N);
            showMemoryUsage("After secondary memory allocation");
        } catch (OutOfMemoryError e) {
            showMemoryUsage("!!!! Out of memory error !!!!");
            System.out.println();
        }
    }

    // function to allocate and return a reference to a lot of memory
    private static ArrayList<String> generateLargeStringsArray(int N) {
        ArrayList<String> strings = new ArrayList<>(N);
        for (int i = 0; i < N; i++) {
            StringBuilder sb = new StringBuilder(N);
            for (int j = 0; j < N; j++) {
                sb.append((char)Math.round(Math.random() * 0xFFFF));
            }
            strings.add(sb.toString());
        }

        return strings;
    }

    // helper method to display current memory status
    public static void showMemoryUsage(String action) {
        long free = Runtime.getRuntime().freeMemory();
        long total = Runtime.getRuntime().totalMemory();
        long max = Runtime.getRuntime().maxMemory();
        long used = total - free;
        System.out.printf("\t%40s: %10dk of max %10dk%n", action, used / 1024, max / 1024);
    }
}
    for (String string : strings);//引发outofmomery异常
     //for(int i=0;i<strings.size();i++);//正常
    
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,968评论 6 482
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,601评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 153,220评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,416评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,425评论 5 374
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,144评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,432评论 3 401
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,088评论 0 261
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,586评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,028评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,137评论 1 334
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,783评论 4 324
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,343评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,333评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,559评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,595评论 2 355
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,901评论 2 345

推荐阅读更多精彩内容

  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 12,693评论 2 59
  • 转载自:https://halfrost.com/go_map_chapter_one/ https://half...
    HuJay阅读 6,124评论 1 5
  • 还是一天的推广任务,今天我们去阜阳的简爱城,申寨小区都还是很不错的效果。感觉自己对阜阳是越来越熟悉了。好了晚安! ...
    吴三石石石石ah阅读 293评论 0 0
  • 今早漫天的雪花纷纷扬扬、混沌了天地,浪漫了人间。可落寞了旅途,寂寥了归人。 在路上偶遇突然而猛烈的鹅毛大雪,大朵小...
    宸圭阅读 1,056评论 18 32
  • 之前看到别人健身,心想那么瘦了,健身有什么意义。 从今年开始,我依然很瘦,但是明显感觉腿部和肚子上有种奇怪的感觉,...
    粉饰依然阅读 532评论 4 5