深入理解Tomcat(12)拾遗-MessageBytes

前言

Tomcat为了提高性能,在接受到socket传入的字节之后并不会马上进行编码转换,而是保持byte[]的方式,在用到的时候再进行转换。在tomcat的实现中,MessageBytes正是byte[]的抽象。本节我们就来深入了解一下!

如何使用?

我们通过一个简单的例子来看看MessageBytes是如何使用的。这个例子用于提取byte[]里面的一个子byte[],然后打印输出。

public static void main(String[] args) {
    // 构造`MessageBytes`对象
    MessageBytes mb = MessageBytes.newInstance();
    // 待测试的`byte[]`对象
    byte[] bytes = "abcdefg".getBytes(Charset.defaultCharset());
    // 调用`setBytes()`对bytes进行标记
    mb.setBytes(bytes, 2, 3);
    // 转换为字符串进行控制台输出
    System.out.println(mb.toString());
}

我们运行一下,看到下面输出,的确和我们预料的一致。

效果图

源码解读

无源码无真相,我们这就来分析一下源码。在MessageBytes里面一共有四种类型,用于表示消息的类型。

  1. T_NULL表示空消息,即消息为null
  2. T_STR表示消息为字符串类型
  3. T_BYTES表示消息为字节数组类型
  4. T_CHARS表示消息为字符数组类型
// primary type ( whatever is set as original value )
private int type = T_NULL;

public static final int T_NULL = 0;
/** getType() is T_STR if the the object used to create the MessageBytes
    was a String */
public static final int T_STR  = 1;
/** getType() is T_BYTES if the the object used to create the MessageBytes
    was a byte[] */
public static final int T_BYTES = 2;
/** getType() is T_CHARS if the the object used to create the MessageBytes
    was a char[] */
public static final int T_CHARS = 3;

接着我们看看构造方法,默认构造方法居然是private类型的,同时提供了工厂方法用于创建MessageBytes实例。

/**
 * Creates a new, uninitialized MessageBytes object.
 * Use static newInstance() in order to allow
 *   future hooks.
 */
private MessageBytes() {
}

/**
 * Construct a new MessageBytes instance.
 * @return the instance
 */
public static MessageBytes newInstance() {
    return factory.newInstance();
}

我们接着看看关键方法setBytes(),该方法内部调用了ByteChunk.setBytes()方法,同时设置了type字段

// Internal objects to represent array + offset, and specific methods
private final ByteChunk byteC=new ByteChunk();
private final CharChunk charC=new CharChunk();

/**
 * Sets the content to the specified subarray of bytes.
 *
 * @param b the bytes
 * @param off the start offset of the bytes
 * @param len the length of the bytes
 */
public void setBytes(byte[] b, int off, int len) {
    byteC.setBytes( b, off, len );
    type=T_BYTES;
    hasStrValue=false;
    hasHashCode=false;
    hasLongValue=false;
}

我们深入去看看ByteChunk.setBytes()。非常简单,就是设置一下待标识的字节数组开始位置结束位置

private byte[] buff; // 待标记的字节数组
protected int start; // 开始位置
protected int end; // 结束位置
protected boolean isSet; // 是否已经设置过了
protected boolean hasHashCode = false; // 是否有hashCode

/**
 * Sets the buffer to the specified subarray of bytes.
 *
 * @param b the ascii bytes
 * @param off the start offset of the bytes
 * @param len the length of the bytes
 */
public void setBytes(byte[] b, int off, int len) {
    buff = b;
    start = off;
    end = start + len;
    isSet = true;
    hasHashCode = false;
}

既然字节数组已经标识过了,那什么时候用呢?我们能想到的自然就是转换为String,而转换的地方一般是调用对象的toString()方法,我们来看看MessageBytes.toString()方法。

@Override
public String toString() {
    if( hasStrValue ) {
        return strValue;
    }

    switch (type) {
    case T_CHARS:
        strValue=charC.toString();
        hasStrValue=true;
        return strValue;
    case T_BYTES:
        strValue=byteC.toString();
        hasStrValue=true;
        return strValue;
    }
    return null;
}

首先判断是否有缓存的字符串,有的话就直接返回,这也是提高性能的一种方式。其次是根据type来选择不同的*Chunk,然后调用其toString()方法。那么我们这儿选择ByteChunk.toString()来分析。

@Override
public String toString() {
    if (null == buff) {
        return null;
    } else if (end - start == 0) {
        return "";
    }
    return StringCache.toString(this);
}

调用了StringCache.toString(this)StringCache,顾名思义,就是对字符串进行缓存,不过本节我们主要分析MessageBytes,所以会忽略其缓存的代码。下面来看看这个方法,该方法非常长,前方高能!

public static String toString(ByteChunk bc) {
    // If the cache is null, then either caching is disabled, or we're
    // still training
    if (bcCache == null) {
        String value = bc.toStringInternal();
        if (byteEnabled && (value.length() < maxStringSize)) {
            // If training, everything is synced
            synchronized (bcStats) {
                // If the cache has been generated on a previous invocation
                // while waiting for the lock, just return the toString
                // value we just calculated
                if (bcCache != null) {
                    return value;
                }
                // Two cases: either we just exceeded the train count, in
                // which case the cache must be created, or we just update
                // the count for the string
                if (bcCount > trainThreshold) {
                    long t1 = System.currentTimeMillis();
                    // Sort the entries according to occurrence
                    TreeMap<Integer,ArrayList<ByteEntry>> tempMap =
                            new TreeMap<>();
                    for (Entry<ByteEntry,int[]> item : bcStats.entrySet()) {
                        ByteEntry entry = item.getKey();
                        int[] countA = item.getValue();
                        Integer count = Integer.valueOf(countA[0]);
                        // Add to the list for that count
                        ArrayList<ByteEntry> list = tempMap.get(count);
                        if (list == null) {
                            // Create list
                            list = new ArrayList<>();
                            tempMap.put(count, list);
                        }
                        list.add(entry);
                    }
                    // Allocate array of the right size
                    int size = bcStats.size();
                    if (size > cacheSize) {
                        size = cacheSize;
                    }
                    ByteEntry[] tempbcCache = new ByteEntry[size];
                    // Fill it up using an alphabetical order
                    // and a dumb insert sort
                    ByteChunk tempChunk = new ByteChunk();
                    int n = 0;
                    while (n < size) {
                        Object key = tempMap.lastKey();
                        ArrayList<ByteEntry> list = tempMap.get(key);
                        for (int i = 0; i < list.size() && n < size; i++) {
                            ByteEntry entry = list.get(i);
                            tempChunk.setBytes(entry.name, 0,
                                    entry.name.length);
                            int insertPos = findClosest(tempChunk,
                                    tempbcCache, n);
                            if (insertPos == n) {
                                tempbcCache[n + 1] = entry;
                            } else {
                                System.arraycopy(tempbcCache, insertPos + 1,
                                        tempbcCache, insertPos + 2,
                                        n - insertPos - 1);
                                tempbcCache[insertPos + 1] = entry;
                            }
                            n++;
                        }
                        tempMap.remove(key);
                    }
                    bcCount = 0;
                    bcStats.clear();
                    bcCache = tempbcCache;
                    if (log.isDebugEnabled()) {
                        long t2 = System.currentTimeMillis();
                        log.debug("ByteCache generation time: " +
                                (t2 - t1) + "ms");
                    }
                } else {
                    bcCount++;
                    // Allocate new ByteEntry for the lookup
                    ByteEntry entry = new ByteEntry();
                    entry.value = value;
                    int[] count = bcStats.get(entry);
                    if (count == null) {
                        int end = bc.getEnd();
                        int start = bc.getStart();
                        // Create byte array and copy bytes
                        entry.name = new byte[bc.getLength()];
                        System.arraycopy(bc.getBuffer(), start, entry.name,
                                0, end - start);
                        // Set encoding
                        entry.charset = bc.getCharset();
                        // Initialize occurrence count to one
                        count = new int[1];
                        count[0] = 1;
                        // Set in the stats hash map
                        bcStats.put(entry, count);
                    } else {
                        count[0] = count[0] + 1;
                    }
                }
            }
        }
        return value;
    } else {
        accessCount++;
        // Find the corresponding String
        String result = find(bc);
        if (result == null) {
            return bc.toStringInternal();
        }
        // Note: We don't care about safety for the stats
        hitCount++;
        return result;
    }
}

看完了,第一感觉就是该方法好长啊!但是通过层层剥减,我们发现关键的地方不多,下面我们把非关键的地方去掉看看。

  1. 省略掉的缓存部分
  2. 这儿其实又调回了ByteChunk,调用的方法为toStringInternal()
public static String toString(ByteChunk bc) {

    // If the cache is null, then either caching is disabled, or we're
    // still training
    if (bcCache == null) {
        String value = bc.toStringInternal();
        // 1. 省略掉的缓存部分
        return value;
    } else {
        accessCount++;
        // Find the corresponding String
        String result = find(bc);
        if (result == null) {
            // 2. 这儿其实又调回了`ByteChunk`,调用的方法为`toStringInternal()`
            return bc.toStringInternal();
        }
        // Note: We don't care about safety for the stats
        hitCount++;
        return result;
    }
}

我们看看ByteChunk.toStringInternal()方法,猜想这儿才是关键的地方!

public String toStringInternal() {
    if (charset == null) {
        charset = DEFAULT_CHARSET;
    }
    // new String(byte[], int, int, Charset) takes a defensive copy of the
    // entire byte array. This is expensive if only a small subset of the
    // bytes will be used. The code below is from Apache Harmony.
    CharBuffer cb = charset.decode(ByteBuffer.wrap(buff, start, end - start));
    return new String(cb.array(), cb.arrayOffset(), cb.length());
}

果然如此!这儿正是根据偏移量待提取长度进行编码提取转换

需要特别注意toStringInternal()的内部注释,该注释已经给出了使用java.nio.charset.CharSet.decode()代替直接使用new String(byte[], int, int, Charset)的原因。因为很多时候,我们往往只提取一个大的byte[]里面很小的一部分byte[]。如果使用new String(byte[], int, int, Charset),将会对整个byte数组进行拷贝,严重影响性能。

总结

通过阅读tomcat中byte[]转String的源码,我们看到tomcat开发团队可谓是费尽心思地提高web服务器的性能。转换的思路也很简单,就是通过打标记+延时提取的方式来实现按需使用。通过在编码提取转换的时候使用了特殊的转换逻辑,让楼主大开眼界!

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容

  • 一、上周计划执行情况 : 早起:打卡第313天,最早起床05:05,平均起床时间:05:33。 运动:平板1次每组...
    金玉满满阅读 162评论 0 1
  • 一年级的时候还有一位同学是印象很深的。比我高比我壮,下课后经常一起玩游戏例如拍纸牌,每次我都能赢他一些纸牌,虽然他...
    老徐在路上阅读 317评论 0 0
  • 2017.11.28 无锡,没有想象中的冷。或许,没是时候; 偶尔,也下起一滴一滴有某种含蓄、略带优愁的小雨…… ...
    咖啡移动阅读 196评论 0 2