Java Buffer
1.1 NIO Buffers - Class java.nio.Buffer
NIO data transfer is through the so-called buffers implemented in java.nio.Buffer class. A Buffer is similar to an array, except that it's implemented much more efficiently by closely coupled with the underlying OS.A Buffer is a contiguous, linear storage. Similar to an array, a Buffer has a fixed capacity.
The Buffer class for each of the primitibe types(except boolean), as shown in the above diagram. The abstarct superclass java.nio.Buffer provides the common properties and some common operatons of all buffers.
A Buffer
has a capacity, position, limit, and an optional mark:
- The capacity must be specified when the
Buffer
is constructed and cannot be changed (similar to an array). You can retrieve it via methodcapacity()
. - The limit specifies the current occupancy. In other word, the buffer contains valid data in the range 0 to limit-1. You can retrieve the current limit via method
limit()
or set thelimit
via methodlimit(int newLimit)
. Limit shall not be greater than capacity. - Unlike array, there is a so-called position (or cursor) in a
Buffer
that indicates where the next piece of data is to be read or written. You can retrieve the current position via methodposition()
or change the current position via methodposition(int newPosition)
. Position shall not be greater than the limit. - A mark provide a positional marker. You can mark the current position via the method
mark()
.
Data Transfer (Get/Put):
Each of the primitive buffers provides a set of get()
and put()
methods to read/write an element or a array of elements from/to the buffer. The position increases by the number of elements transferred. For example, the IntBuffer
provides:
ByteBuffer
is special. It provides additional getXxx()
/putXxx()
methods to parse raw bytes into other primitive types. It also can be used as the sources and targets of I/O operations, which will be explained later in channel I/O.
Mark and Reset:
You can use mark()
method to mark the current position. Invoking reset()
sets the position to the previously-marked position. The mark may or may not be set. If the mark is not set, invoking reset()
triggers an InvalidMarkException
. If the mark is set, it should never be greater than the position (because the mark() marks the current position and position advances). The mark will be discarded when the position or the limit is adjusted to a value smaller than the mark. Hence, 0 ≤ mark ≤ position ≤ limit ≤ capacity.
Clear, Flip and Rewind:
clear()
: sets theposition
to 0,limit
to thecapacity
, and discardsmark
. It prepares the buffer for input.flip()
: sets thelimit
to the currentposition
,position
to 0, and discardmark
. Buffer populated and ready for output.rewind()
: set the position to 0, and discard mark. It prepares the buffer for re-read.
Creating a Buffer: There are 3 ways to create a buffer:
- via method
allocate(int capacity)
, which allocates a new buffer, sets position to 0 and limit to capacity, and clear the mark. - wrap an existing array into buffer via
wrap(type[] array, int offset, int length)
orwrap(type[] array)
method. - by creating a view of an existing
ByteBuffer
(to be discussed later).
Slicing and data sharing:
The slice() method creates sub-buffer from an existing buffer. That is it creates a new buffer sharing a portion of the original buffer.
We can see a example:
Then we alter elements in the buffer(two buffers and the sub-buffers share the same underlying data array).
Here is the ouput:
before alter sub-buffer:0 1 2 3 4 5 6 7 8 9
alter elements in sub buffer.
After altering sub buffer0 1 2 33 44 55 66 7 8 9
Read-only buffers
Read-only buffers means only read operation allowed. We can turn any regular buffer into a read-only buffer by calling its asReadOnlyBuffer()
method, which returns a new buffer that is identical to the first (and shares data with it), but is read-only. But we can not turn an read-only buffer to writable buffer.
Direct and in Direct buffer
To see the difference between these two buffer, please see Analysis about different methods for reading and writing file in Java language.
Memory-mapped file I/O
Memory-mapped file I/O can read and write file more fast than regular stream or channel based I/O.
Memory-mapped file I/O is accomplished by causing the data in a file to magically appear as the contents of a memory array. For it provide access to the facility that OS implement FS by mapping portions of a file into portions of memory, doing so on demand.
Mapping a file into memory example:
static void MappingFileMem() throws IOException{
String inFileStr = "/users/wsy/Documents/job/kimchi_v2.pdf";
String outFileStr = "./kimchi_v2.pdf";
long startTime, elapsedTime; // for speed benchmarking
int bufferSizeKB = 4;
int bufferSize = bufferSizeKB * 1024;
FileInputStream input = new FileInputStream(inFileStr);
FileChannel channel = input.getChannel(); MappedByteBuffer mbb = channel.map(FileChannel.MapMode.READ_WRITE, 0, 1024);
}
Scattering and gathering
Scatter/gather I/O is a method of reading and writing that uses multiple buffers, rather than a single buffer. A scatter read reads data into a array of buffers rather than a single buffer. A gathering write writes data from a array of buffers rather than a single buffer.
Applications of scatter/gather:
Scatter/gather I/O is useful for dividing a piece of data into sections. For example, we can write a networking app that uses message objects, and each messages divided into a fixed-length header and body We can create 2 buffers, one for the header, and other for the body.When we put these 2 in an array and read data into them by scattering read, then the header and body will be neatly divided into 2 buffers. The scatter read will automatically find the first with room in it. After the previous filled, it movs to the next one.
long read( ByteBuffer[] dsts );
long read( ByteBuffer[] dsts, int offset, int length );
Gathering writes is like the Scattering reads.
Java Buffer的更多相关文章
- Java学习笔记20(String类应用、StringBuffer类、StringBuilder类)
1.获取指定字符串中大小写和数字的个数: package demo; public class StringTest { public static void main(String[] args) ...
- Java IO、NIO、AIO知识总结
本文主要讲述下自己对IO的理解,对IO的用法和细则可能没有顾虑到. 本文的理解基于以下几篇文章,他们对各自部分都讲的很细,对我理解IO提供了很大帮助. https://www.cnblogs.com/ ...
- 【JAVA语法】01Java-变量与数据类型
数据类型初阶 基本数据类型的包装类 整数类型&浮点类型&字符类型 大小类型转换 通过Scanner从控制台获取数据 变量相关基础算法 Java的错误类型 字符串String 补充-Pa ...
- java#tostring
通常使用apache-commons 来生成tostring方法,但是对于类型为java.util.Date的字段打印效果并不是我们想要的. @Override public String toStr ...
- Android OpenGL ES(三)OpenGL ES API 命名习惯 .
OpenGL ES是个跨平台的3D图形开发包规范,最常见的实现是采用C语言实现的,Android OpenGL ES 实现上是使用Java 语言对底层的C接口进行了封装,因此在android.open ...
- 代码生成器实现的Entity,Dao,Service,Controller,JSP神器(含代码附件)
package com.flong.codegenerator; import java.sql.Connection; import java.sql.DatabaseMetaData; impor ...
- 11jsp
1.JSP 1. 指令 作用:用于配置JSP页面,导入资源文件 格式: <%@ 指令名称 属性名1=属性值1 属性名2=属性值2 ... %> 分类: ...
- SprinfJdbcTemplate+SpringMVC 代码生成器实现的Entity,Dao,Service,Controller,JSP神器(含代码附件)
代码生成器实现的Entity,Dao,Service,Controller,JSP神器(含代码附件) 原文地址: http://jilongliang.iteye.com/blog/2262070 p ...
- Spark案例分析
一.需求:计算网页访问量前三名 import org.apache.spark.rdd.RDD import org.apache.spark.{SparkConf, SparkContext} /* ...
随机推荐
- Apache Tomcat Not Showing in Eclipse Server Runtime Environments
In my case I needed to install "JST Server Adapters". I am running Eclipse 3.6 Helios RCP ...
- 众数问题(为什么只能输入一组数据,不能输入m组数据)
描述 所谓众数,就是对于给定的含有N个元素的多重集合,每个元素在S中出现次数最多的成为该元素的重数, 多重集合S重的重数最大的元素成为众数.例如:S={1,2,2,2,3,5},则多重集S的众数是2, ...
- Linux学习sed命令
sed 是一种在线编辑器,它一次处理一行内容.处理时,把当前处理的行存储在临时缓冲区中,称为“模式空间”(pattern space),接着用sed命令处理缓冲区中的内容,处理完成后,把缓冲区的内容送 ...
- 使用fastcgi_cache加速网站
为了提高网站的性能缓存是一把利器,nginx中可以配置fastcig_cache来缓存不需要实时获取的数据实现动静分离,nginx.conf配置如下: http { - fastcgi ...
- 浮动层固定兼容IE6 position:fixed的最佳解决方案
第一种:css方法 有时候当我们需要把一个元素固定在页面的某个部位,一般都是用css中的“position:fixed;”方法来解决,但是IE6不支持fixed,所以今天分享一个兼容IE6的页面底部固 ...
- Eclipse 打包过滤 Log.e
我们在开发时,经常会输出各种日志来debug代码.但是等到应用发布的apk运行时不希望它输出日志. 关闭输出日志Log.v(),Log.i(),Log.w(),Log.v(),Log.e()等 原理: ...
- JBoss部属和EJB调用-EJB3.0入门经典学习笔记(2)
目录 1. 在JBoss中部属 2. 在Tomcat中调用EJB 3. 在JBoss中调用EJB 1. 在JBoss中部属 1) JBoss的配置目录 路径D:\Java\jboss6\serv ...
- codeforces 15D . Map 优先队列
题目链接 题目意思很简单nm的矩阵里, 选若干个ab的小矩阵, 定义每个矩阵的值为这个矩阵里的所有数的和-最小值*数的个数. 选小矩阵时, 优先选值最小的,然后次小的.. 知道不能选位置. 输出所有矩 ...
- poj2350
#include <stdio.h> #include <stdlib.h> int main() { ],tim,i; scanf("%d",&n ...
- UberX及以上级别车奖励政策(优步北京第四组)
优步北京第四组: 定义为2015年7月20日至今激活的司机(以优步后台数据显示为准) 滴滴快车单单2.5倍,注册地址:http://www.udache.com/如何注册Uber司机(全国版最新最详细 ...