文档章节

java.nio.ByteBuffer源码解读

A__17
 A__17
发布于 2017/08/21 23:04
字数 2008
阅读 2
收藏 0
点赞 0
评论 0

版本:JDK7

package java.nio;

public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer> {

// These fields are declared here rather than in Heap-X-Buffer in order to
// reduce the number of virtual method invocations needed to access these
// values, which is especially costly when coding small buffers.
//
final byte[] hb;                  // Non-null only for heap buffers
final int offset;
boolean isReadOnly;                 // Valid only for heap buffers


ByteBuffer(int mark, int pos, int lim, int cap, byte[] hb, int offset) {
    super(mark, pos, lim, cap);
    this.hb = hb;
    this.offset = offset;
}

ByteBuffer(int mark, int pos, int lim, int cap) { // package-private
    this(mark, pos, lim, cap, null, 0);
}


// 创建一个容量为capacity的ByteBuffer对象
public static ByteBuffer allocateDirect(int capacity) {
    return new DirectByteBuffer(capacity);
}


// 创建一个容量为capacity的ByteBuffer对象
public static ByteBuffer allocate(int capacity) {
    if (capacity < 0) throw new IllegalArgumentException();
    return new HeapByteBuffer(capacity, capacity);
}


public static ByteBuffer wrap(byte[] array, int offset, int length) {
    try {
        return new HeapByteBuffer(array, offset, length);
    } catch (IllegalArgumentException x) {
        throw new IndexOutOfBoundsException();
    }
}

public static ByteBuffer wrap(byte[] array) {
    return wrap(array, 0, array.length);
}

public abstract ByteBuffer slice();
public abstract ByteBuffer duplicate();
public abstract ByteBuffer asReadOnlyBuffer();

/**
 * Reads the byte at this buffer's position, and then increments the position.
 */
// 读取单个字节,并将position自增1
public abstract byte get();

/**
 * Writes the given byte into this buffer at the current position, and then increments the position. 
 */
// 将给定的单个字节写入缓冲区的当前位置,并将position自增1
public abstract ByteBuffer put(byte b);


// 读取指定位置的字节,注意:不会改变position
public abstract byte get(int index);

// 将给定的单个字节写入缓冲区的index位置,注意:不会改变position
public abstract ByteBuffer put(int index, byte b);


// -- Bulk get operations --
/**
 * This method transfers bytes from this buffer into the given destination array. 
 */
// (从Buffer中)读取多个字节(从索引offset开始,读取length长度的数据)到dst中,如果Buffer剩余的空间小于length,则抛异常
public ByteBuffer get(byte[] dst, int offset, int length) {
    checkBounds(offset, length, dst.length);
    if (length > remaining())
        throw new BufferUnderflowException();
    int end = offset + length;
    for (int i = offset; i < end; i++)
        dst[i] = get();
    return this;
}

/**
 * This method transfers bytes from this buffer into the given destination array.
 */
// 批量读取dst.length个字节到dst中,如果Buffer剩余的空间小于dst的length,则抛异常
public ByteBuffer get(byte[] dst) {
    return get(dst, 0, dst.length);
}

// -- Bulk put operations --
/**
 * 将src中的数据写入Buffer的当前位置
 */
public ByteBuffer put(ByteBuffer src) {
    if (src == this)
        throw new IllegalArgumentException();
    int n = src.remaining();
    if (n > remaining())
        throw new BufferOverflowException();
    for (int i = 0; i < n; i++)
        put(src.get());
    return this;
}

public ByteBuffer put(byte[] src, int offset, int length) {
    checkBounds(offset, length, src.length);
    if (length > remaining())
        throw new BufferOverflowException();
    int end = offset + length;
    for (int i = offset; i < end; i++)
        this.put(src[i]);
    return this;
}

public final ByteBuffer put(byte[] src) {
    return put(src, 0, src.length);
}


// -- Other stuff --

/**
 * Tells whether or not this buffer is backed by an accessible byte array.
 *
 * <p> If this method returns <tt>true</tt> then the {[@link](https://my.oschina.net/u/393) #array() array}
 * and {[@link](https://my.oschina.net/u/393) #arrayOffset() arrayOffset} methods may safely be invoked.
 * </p>
 *
 * [@return](https://my.oschina.net/u/556800)  <tt>true</tt> if, and only if, this buffer
 *          is backed by an array and is not read-only
 */
public final boolean hasArray() {
    return (hb != null) && !isReadOnly;
}

/**
 * Returns the byte array that backs this
 * buffer  <i>(optional operation)</i>.
 *
 * <p> Modifications to this buffer's content will cause the returned
 * array's content to be modified, and vice versa.
 *
 * <p> Invoke the {[@link](https://my.oschina.net/u/393) #hasArray hasArray} method before invoking this
 * method in order to ensure that this buffer has an accessible backing
 * array.  </p>
 *
 * [@return](https://my.oschina.net/u/556800)  The array that backs this buffer
 *
 * @throws  ReadOnlyBufferException
 *          If this buffer is backed by an array but is read-only
 *
 * @throws  UnsupportedOperationException
 *          If this buffer is not backed by an accessible array
 */
public final byte[] array() {
    if (hb == null) throw new UnsupportedOperationException();
    if (isReadOnly) throw new ReadOnlyBufferException();
    return hb;
}

/**
 * Returns the offset within this buffer's backing array of the first
 * element of the buffer  <i>(optional operation)</i>.
 *
 * <p> If this buffer is backed by an array then buffer position <i>p</i>
 * corresponds to array index <i>p</i> + <tt>arrayOffset()</tt>.
 *
 * <p> Invoke the {@link #hasArray hasArray} method before invoking this
 * method in order to ensure that this buffer has an accessible backing
 * array.  </p>
 *
 * @return  The offset within this buffer's array
 *          of the first element of the buffer
 *
 * @throws  ReadOnlyBufferException
 *          If this buffer is backed by an array but is read-only
 *
 * @throws  UnsupportedOperationException
 *          If this buffer is not backed by an accessible array
 */
public final int arrayOffset() {
    if (hb == null) throw new UnsupportedOperationException();
    if (isReadOnly) throw new ReadOnlyBufferException();
    return offset;
}

/**
 * Compacts this buffer. 压缩并整理Buffer。
 *
 * The bytes between the buffer's current position and its limit, if any, are copied to the beginning of the buffer.
 * That is, the byte at index p=position() is copied to index zero, 
 * the byte at index p+1 is copied to index one, 
 * and so forth until the byte at index limit()-1 is copied to index n=limit()-1-p 
 * The buffer's position is then set to n+1 and its limit is set to its capacity.  The mark, if defined, is discarded.
 * 
 * 即:将所有未读的数据拷贝到Buffer的起始处,然后将position设到最后一个未读元素的后面
 * limit设置为capacity,此时,如果向Buffer中写数据,则不会覆盖之前未读的数据!
 * 与clear()方法的比较:
 * 		如果Buffer中存在未读的数据,调用clear()方法后,这些未读的数据将会被“遗忘”,因为在clear之后,position的值为0,故无法确定未读数据的位置。
 */
public abstract ByteBuffer compact();

/**
 * Tells whether or not this byte buffer is direct. </p>
 */
public abstract boolean isDirect();


public String toString() {
    StringBuffer sb = new StringBuffer();
    sb.append(getClass().getName());
    sb.append("[pos=");
    sb.append(position());
    sb.append(" lim=");
    sb.append(limit());
    sb.append(" cap=");
    sb.append(capacity());
    sb.append("]");
    return sb.toString();
}

/**
 * Returns the current hash code of this buffer.
 */
public int hashCode() {
    int h = 1;
    int p = position();
    for (int i = limit() - 1; i >= p; i--)
        h = 31 * h + (int)get(i);
    return h;
}

/**
 * Tells whether or not this buffer is equal to another object.
 *
 * They have the same element type,
 * They have the same number of remaining elements,
 * and The two sequences of remaining elements, 
 * considered independently of their starting positions, are pointwise equal.
 * 
 * 即:Buffer中元素的类型相同,并且剩余的元素完全相同,则返回true
 * 注意:并不是比较Buffer的所有数据,只是比较Buffer中的剩余数据。
 */
public boolean equals(Object ob) {
    if (this == ob)
        return true;
    if (!(ob instanceof ByteBuffer))
        return false;
    ByteBuffer that = (ByteBuffer)ob;
    if (this.remaining() != that.remaining())
        return false;
    int p = this.position();
    for (int i = this.limit() - 1, j = that.limit() - 1; i >= p; i--, j--)
        if (!equals(this.get(i), that.get(j)))
            return false;
    return true;
}

private static boolean equals(byte x, byte y) {
    return x == y;
}

/**
 * Compares this buffer to another.
 *
 * 比较两个Buffer的剩余元素
 * 一个Buffer“小于”另一个Buffer的场景:
 * 		第一个不相等的元素小于另一个Buffer中对应的元素
 * 		所有元素都相等,但是第一个Buffer的元素个数小于另一个Buffer的个数
 */
public int compareTo(ByteBuffer that) {
    int n = this.position() + Math.min(this.remaining(), that.remaining());
    for (int i = this.position(), j = that.position(); i < n; i++, j++) {
        int cmp = compare(this.get(i), that.get(j));
        if (cmp != 0)
            return cmp;
    }
    return this.remaining() - that.remaining();
}

private static int compare(byte x, byte y) {
    return Byte.compare(x, y);
}

// -- Other char stuff --

// -- Other byte stuff: Access to binary data --


boolean bigEndian = true;                                  // package-private
    
boolean nativeByteOrder = (Bits.byteOrder() == ByteOrder.BIG_ENDIAN);	// package-private
   

/**
 * Retrieves this buffer's byte order.
 *
 * <p> The byte order is used when reading or writing multibyte values, and
 * when creating buffers that are views of this byte buffer.  The order of
 * a newly-created byte buffer is always {@link ByteOrder#BIG_ENDIAN
 * BIG_ENDIAN}.  </p>
 *
 * @return  This buffer's byte order
 */
public final ByteOrder order() {
    return bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN;
}

/**
 * Modifies this buffer's byte order.  </p>
 *
 * @param  bo
 *         The new byte order,
 *         either {@link ByteOrder#BIG_ENDIAN BIG_ENDIAN}
 *         or {@link ByteOrder#LITTLE_ENDIAN LITTLE_ENDIAN}
 *
 * @return  This buffer
 */
public final ByteBuffer order(ByteOrder bo) {
    bigEndian = (bo == ByteOrder.BIG_ENDIAN);
    nativeByteOrder = (bigEndian == (Bits.byteOrder() == ByteOrder.BIG_ENDIAN));
    return this;
}

// Unchecked accessors, for use by ByteBufferAs-X-Buffer classes
//
abstract byte _get(int i);                          // package-private
abstract void _put(int i, byte b);                  // package-private


/**
 * Relative <i>get</i> method for reading an int value.
 *
 * <p> Reads the next four bytes at this buffer's current position,
 * composing them into an int value according to the current byte order,
 * and then increments the position by four.  </p>
 *
 * @return  The int value at the buffer's current position
 *
 * @throws  BufferUnderflowException
 *          If there are fewer than four bytes
 *          remaining in this buffer
 */
public abstract int getInt();

/**
 * Relative <i>put</i> method for writing an int
 * value  <i>(optional operation)</i>.
 *
 * <p> Writes four bytes containing the given int value, in the
 * current byte order, into this buffer at the current position, and then
 * increments the position by four.  </p>
 *
 * @param  value
 *         The int value to be written
 *
 * @return  This buffer
 *
 * @throws  BufferOverflowException
 *          If there are fewer than four bytes
 *          remaining in this buffer
 *
 * @throws  ReadOnlyBufferException
 *          If this buffer is read-only
 */
public abstract ByteBuffer putInt(int value);

/**
 * Absolute <i>get</i> method for reading an int value.
 *
 * <p> Reads four bytes at the given index, composing them into a
 * int value according to the current byte order.  </p>
 *
 * @param  index
 *         The index from which the bytes will be read
 *
 * @return  The int value at the given index
 *
 * @throws  IndexOutOfBoundsException
 *          If <tt>index</tt> is negative
 *          or not smaller than the buffer's limit,
 *          minus three
 */
public abstract int getInt(int index);

/**
 * Absolute <i>put</i> method for writing an int
 * value  <i>(optional operation)</i>.
 *
 * <p> Writes four bytes containing the given int value, in the
 * current byte order, into this buffer at the given index.  </p>
 *
 * @param  index
 *         The index at which the bytes will be written
 *
 * @param  value
 *         The int value to be written
 *
 * @return  This buffer
 *
 * @throws  IndexOutOfBoundsException
 *          If <tt>index</tt> is negative
 *          or not smaller than the buffer's limit,
 *          minus three
 *
 * @throws  ReadOnlyBufferException
 *          If this buffer is read-only
 */
public abstract ByteBuffer putInt(int index, int value);

/**
 * Creates a view of this byte buffer as an int buffer.
 *
 * <p> The content of the new buffer will start at this buffer's current
 * position.  Changes to this buffer's content will be visible in the new
 * buffer, and vice versa; the two buffers' position, limit, and mark
 * values will be independent.
 *
 * <p> The new buffer's position will be zero, its capacity and its limit
 * will be the number of bytes remaining in this buffer divided by
 * four, and its mark will be undefined.  The new buffer will be direct
 * if, and only if, this buffer is direct, and it will be read-only if, and
 * only if, this buffer is read-only.  </p>
 *
 * @return  A new int buffer
 */
public abstract IntBuffer asIntBuffer();

// ...

}

© 著作权归作者所有

共有 人打赏支持
A__17
粉丝 2
博文 89
码字总数 101178
作品 0
朝阳
Android6.0源码解读之Activity点击事件分发机制

本篇博文是Android点击事件分发机制系列博文的第四篇,主要是从解读Activity类的源码入手,根据源码理清Activity点击事件分发原理,并掌握Activity点击事件分法机制。特别声明的是,本源码解...

mynameishuangshuai ⋅ 2016/10/23 ⋅ 0

Android6.0源码解读之View点击事件分发机制

本篇博文是Android点击事件分发机制系列博文的第二篇,主要是从解读View类的源码入手,根据源码理清View点击事件分发原理,并掌握View点击事件分法机制。特别声明的是,本源码解读是基于最新...

mynameishuangshuai ⋅ 2016/10/23 ⋅ 0

升级到JDK9的一个BUG,你了解吗

概述 前几天在一个群里看到一个朋友发了一个demo,说是JDK的bug,昨天在JVM的一个群里又有朋友发了,觉得挺有意思,分享给大家,希望大家升级JDK的版本的时候注意下是否存在这样的代码,如果...

你假笨 ⋅ 06/06 ⋅ 0

Drizzle-JDBC 0.5 发布

Drizzle-JDBC 是数据库 Drizzle 的JDBC 驱动程序. This release has some bugfixes. It supports "ON DUPLICATE KEY UPDATE" in the rewrite batch handler. It handles prepared statement......

红薯 ⋅ 2009/09/28 ⋅ 0

Android6.0触摸事件分发机制解读

本篇博文是Android触摸事件分发机制系列博文的第一篇,带领大家从全局掌握Android触摸事件分发机制。特别声明的是,本源码解读是基于最新的Android6.0版本。 (一)Android6.0源码解读之Vie...

mynameishuangshuai ⋅ 2016/10/24 ⋅ 0

关于Birt source的讨论和疑问

最近遇到一个头疼的问题,客户需求使用Myriad-Italic字体显示某些栏位,在模板中设出来以后,并不能正确显示,而是显示成Myriad,也就是说没有斜体。 为什么不能显示成Myriad-Italic呢?这个...

aine_pan ⋅ 2012/09/24 ⋅ 0

Mina系列文章索引

写了很多关于Apache Mina的文章,为了方便大家阅读,我将关于mina的一些文章做点儿索引。 Mina官网资料----------------------------------------------------------------- Mina官网是学习m...

Gaischen ⋅ 2012/11/28 ⋅ 15

Android6.0源码解读之ViewGroup点击事件分发机制

本篇博文是Android点击事件分发机制系列博文的第三篇,主要是从解读ViewGroup类的源码入手,根据源码理清ViewGroup点击事件分发原理,明白ViewGroup和View点击事件分发的关系,并掌握ViewGro...

mynameishuangshuai ⋅ 2016/10/24 ⋅ 0

Yolo的卷积运算源码图解之im2col.c

yolo卷积源码解读找了好久,但网上好多的解读,有点误人子弟, 之前还找到一片注释写的比源代码还多几倍的,以为我就这样看懂了? 不存在的 QWQ,后来直接自己看懂了源码,却看不懂了注释 于是有了下...

蜜丝特潮 ⋅ 05/12 ⋅ 0

今天在网上看到了一个WebSocket的HelloWord,最后与编写的时候遇到一个问题

import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import org.apache.catalina.websocket.MessageInbound; import org.apache.catalina.websocket.WsO......

springsky ⋅ 2013/03/20 ⋅ 1

没有更多内容

加载失败,请刷新页面

加载更多

下一页

Qt中的坑--QTreeWidget添加item 不能显示出来

QTreeWidget* pTree = ui.TreeCheckList; QTreeWidgetItem* item = new QTreeWidgetItem(pTree) ;item->setText ( 0, "test" );pTree->addTopLevelItem (item ); 原因是因为创建一个......

k91191 ⋅ 17分钟前 ⋅ 0

使用Guava的RateLimiter做限流

场景: 1. 在日常生活中,我们肯定收到过不少不少这样的短信,“京东最新优惠卷…”,“天猫送您…”。这种类型的短信是属于推广性质的短信。这种短信一般群发量会到千万级别。然而,要完成这...

wind2012 ⋅ 17分钟前 ⋅ 0

QSlider重新enterEvent

#ifndef DIALOG_H#define DIALOG_H#include <QDialog>namespace Ui {class Dialog;}class Dialog : public QDialog{ Q_OBJECTpublic: explicit Dialog(QW......

xxdd ⋅ 18分钟前 ⋅ 0

生产环境redis备份与恢复

生产环境redis备份与恢复 Tyrant0532 0人评论 1563人阅读 2018-02-01 20:34:10 redis是一个开源(BSD许可),内存存储的数据结构服务器,可用作数据库,高速缓存和消息队列代理。生产中我们主...

rootliu ⋅ 20分钟前 ⋅ 0

nginx中出现403forbidden错误

nginx “403 Forbidden” 错误 出现这个错误一般是因为以下原因: 网站禁止特定的用户访问所有内容,例:网站屏蔽某个ip访问。 访问禁止目录浏览的目录,例:设置autoindex off后访问目录。 ...

河图再现 ⋅ 20分钟前 ⋅ 0

上海云栖:金融政企行业的CDN最佳实践

摘要: 在刚刚结束的上海云栖大会飞天技术汇分论坛上,阿里云视频云产品架构师罗小飞进行了《阿里云CDN——面向金融政企的CDN最佳实践》主题分享,为上海的嘉宾介绍CDN的解决方案与技术服务体...

猫耳m ⋅ 25分钟前 ⋅ 0

docker 基本操作

docker介绍 Docker项目提供了构建在Linux内核功能之上,协同在一起的的高级工具。其目标是帮助开发和运维人员更容易地跨系统跨主机交付应用程序和他们的依赖。Docker通过Docker容器,一个安全...

haoyuehong ⋅ 26分钟前 ⋅ 0

上海云栖:金融政企行业的CDN最佳实践

摘要: 在刚刚结束的上海云栖大会飞天技术汇分论坛上,阿里云视频云产品架构师罗小飞进行了《阿里云CDN——面向金融政企的CDN最佳实践》主题分享,为上海的嘉宾介绍CDN的解决方案与技术服务体...

阿里云云栖社区 ⋅ 29分钟前 ⋅ 0

安装与配置hadoop

一、CentOS7安装 java8,参考centos7.0 安装java1.8,tomcat 二、安装hadoop 版本V3.03 1、下载并解压hadoop # mkdir /usr/local/app# mkdir /usr/local/app/hadoop# cd /usr/local/app/had......

iturtle ⋅ 30分钟前 ⋅ 0

Idea设置Serializable自动生成

File --> Settings --> Editor --> Inspections ->Serialization issues,在该项下找到“Serializable class without 'serialVersionUID' ”并勾选...

Gmupload ⋅ 33分钟前 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部