深入分析:用1K內(nèi)存實(shí)現(xiàn)高效I/O的RandomAccessFile類的詳解
主體:
目前最流行的J2SDK版本是1.3系列。使用該版本的開發(fā)人員需文件隨機(jī)存取,就得使用RandomAccessFile類。其I/O性能較之其它常用開發(fā)語言的同類性能差距甚遠(yuǎn),嚴(yán)重影響程序的運(yùn)行效率。
開發(fā)人員迫切需要提高效率,下面分析RandomAccessFile等文件類的源代碼,找出其中的癥結(jié)所在,并加以改進(jìn)優(yōu)化,創(chuàng)建一個(gè)"性/價(jià)比"俱佳的隨機(jī)文件訪問類BufferedRandomAccessFile。
在改進(jìn)之前先做一個(gè)基本測(cè)試:逐字節(jié)COPY一個(gè)12兆的文件(這里牽涉到讀和寫)。
讀 | 寫 | 耗用時(shí)間(秒) |
RandomAccessFile | RandomAccessFile | 95.848 |
BufferedInputStream + DataInputStream | BufferedOutputStream + DataOutputStream | 2.935 |
我們可以看到兩者差距約32倍,RandomAccessFile也太慢了。先看看兩者關(guān)鍵部分的源代碼,對(duì)比分析,找出原因。
1.1.[RandomAccessFile]
public class RandomAccessFile implements DataOutput, DataInput {
public final byte readByte() throws IOException {
int ch = this.read();
if (ch < 0)
throw new EOFException();
return (byte)(ch);
}
public native int read() throws IOException;
public final void writeByte(int v) throws IOException {
write(v);
}
public native void write(int b) throws IOException;
}
可見,RandomAccessFile每讀/寫一個(gè)字節(jié)就需對(duì)磁盤進(jìn)行一次I/O操作。
1.2.[BufferedInputStream]
public class BufferedInputStream extends FilterInputStream {
private static int defaultBufferSize = 2048;
protected byte buf[]; // 建立讀緩存區(qū)
public BufferedInputStream(InputStream in, int size) {
super(in);
if (size <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
buf = new byte[size];
}
public synchronized int read() throws IOException {
ensureOpen();
if (pos >= count) {
fill();
if (pos >= count)
return -1;
}
return buf[pos++] & 0xff; // 直接從BUF[]中讀取
}
private void fill() throws IOException {
if (markpos < 0)
pos = 0; /* no mark: throw away the buffer */
else if (pos >= buf.length) /* no room left in buffer */
if (markpos > 0) { /* can throw away early part of the buffer */
int sz = pos - markpos;
System.arraycopy(buf, markpos, buf, 0, sz);
pos = sz;
markpos = 0;
} else if (buf.length >= marklimit) {
markpos = -1; /* buffer got too big, invalidate mark */
pos = 0; /* drop buffer contents */
} else { /* grow buffer */
int nsz = pos * 2;
if (nsz > marklimit)
nsz = marklimit;
byte nbuf[] = new byte[nsz];
System.arraycopy(buf, 0, nbuf, 0, pos);
buf = nbuf;
}
count = pos;
int n = in.read(buf, pos, buf.length - pos);
if (n > 0)
count = n + pos;
}
}
1.3.[BufferedOutputStream]
public class BufferedOutputStream extends FilterOutputStream {
protected byte buf[]; // 建立寫緩存區(qū)
public BufferedOutputStream(OutputStream out, int size) {
super(out);
if (size <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
buf = new byte[size];
}
public synchronized void write(int b) throws IOException {
if (count >= buf.length) {
flushBuffer();
}
buf[count++] = (byte)b; // 直接從BUF[]中讀取
}
private void flushBuffer() throws IOException {
if (count > 0) {
out.write(buf, 0, count);
count = 0;
}
}
}
可見,Buffered I/O putStream每讀/寫一個(gè)字節(jié),若要操作的數(shù)據(jù)在BUF中,就直接對(duì)內(nèi)存的buf[]進(jìn)行讀/寫操作;否則從磁盤相應(yīng)位置填充buf[],再直接對(duì)內(nèi)存的buf[]進(jìn)行讀/寫操作,絕大部分的讀/寫操作是對(duì)內(nèi)存buf[]的操作。
1.3.小結(jié)
內(nèi)存存取時(shí)間單位是納秒級(jí)(10E-9),磁盤存取時(shí)間單位是毫秒級(jí)(10E-3), 同樣操作一次的開銷,內(nèi)存比磁盤快了百萬倍。理論上可以預(yù)見,即使對(duì)內(nèi)存操作上萬次,花費(fèi)的時(shí)間也遠(yuǎn)少對(duì)于磁盤一次I/O的開銷。 顯然后者是通過增加位于內(nèi)存的BUF存取,減少磁盤I/O的開銷,提高存取效率的,當(dāng)然這樣也增加了BUF控制部分的開銷。從實(shí)際應(yīng)用來看,存取效率提高了32倍。
根據(jù)1.3得出的結(jié)論,現(xiàn)試著對(duì)RandomAccessFile類也加上緩沖讀寫機(jī)制。
隨機(jī)訪問類與順序類不同,前者是通過實(shí)現(xiàn)DataInput/DataOutput接口創(chuàng)建的,而后者是擴(kuò)展FilterInputStream/FilterOutputStream創(chuàng)建的,不能直接照搬。
2.1.開辟緩沖區(qū)BUF[默認(rèn):1024字節(jié)],用作讀/寫的共用緩沖區(qū)。
2.2.先實(shí)現(xiàn)讀緩沖。
讀緩沖邏輯的基本原理:
A 欲讀文件POS位置的一個(gè)字節(jié)。
B 查BUF中是否存在?若有,直接從BUF中讀取,并返回該字符BYTE。
C 若沒有,則BUF重新定位到該P(yáng)OS所在的位置并把該位置附近的BUFSIZE的字節(jié)的文件內(nèi)容填充BUFFER,返回B。
以下給出關(guān)鍵部分代碼及其說明:
public class BufferedRandomAccessFile extends RandomAccessFile {
// byte read(long pos):讀取當(dāng)前文件POS位置所在的字節(jié)
// bufstartpos、bufendpos代表BUF映射在當(dāng)前文件的首/尾偏移地址。
// curpos指當(dāng)前類文件指針的偏移地址。
public byte read(long pos) throws IOException {
if (pos < this.bufstartpos || pos > this.bufendpos ) {
this.flushbuf();
this.seek(pos);
if ((pos < this.bufstartpos) || (pos > this.bufendpos))
throw new IOException();
}
this.curpos = pos;
return this.buf[(int)(pos - this.bufstartpos)];
}
// void flushbuf():bufdirty為真,把buf[]中尚未寫入磁盤的數(shù)據(jù),寫入磁盤。
private void flushbuf() throws IOException {
if (this.bufdirty == true) {
if (super.getFilePointer() != this.bufstartpos) {
super.seek(this.bufstartpos);
}
super.write(this.buf, 0, this.bufusedsize);
this.bufdirty = false;
}
}
// void seek(long pos):移動(dòng)文件指針到pos位置,并把buf[]映射填充至POS
所在的文件塊。
public void seek(long pos) throws IOException {
if ((pos < this.bufstartpos) || (pos > this.bufendpos)) { // seek pos not in buf
this.flushbuf();
if ((pos >= 0) && (pos <= this.fileendpos) && (this.fileendpos != 0))
{ // seek pos in file (file length > 0)
this.bufstartpos = pos * bufbitlen / bufbitlen;
this.bufusedsize = this.fillbuf();
} else if (((pos == 0) && (this.fileendpos == 0))
|| (pos == this.fileendpos + 1))
{ // seek pos is append pos
this.bufstartpos = pos;
this.bufusedsize = 0;
}
this.bufendpos = this.bufstartpos + this.bufsize - 1;
}
this.curpos = pos;
}
// int fillbuf():根據(jù)bufstartpos,填充buf[]。
private int fillbuf() throws IOException {
super.seek(this.bufstartpos);
this.bufdirty = false;
return super.read(this.buf);
}
}
至此緩沖讀基本實(shí)現(xiàn),逐字節(jié)COPY一個(gè)12兆的文件(這里牽涉到讀和寫,用BufferedRandomAccessFile試一下讀的速度):
讀 | 寫 | 耗用時(shí)間(秒) |
RandomAccessFile | RandomAccessFile | 95.848 |
BufferedRandomAccessFile | BufferedOutputStream + DataOutputStream | 2.813 |
BufferedInputStream + DataInputStream | BufferedOutputStream + DataOutputStream | 2.935 |
可見速度顯著提高,與BufferedInputStream+DataInputStream不相上下。
2.3.實(shí)現(xiàn)寫緩沖。
寫緩沖邏輯的基本原理:
A欲寫文件POS位置的一個(gè)字節(jié)。
B 查BUF中是否有該映射?若有,直接向BUF中寫入,并返回true。
C若沒有,則BUF重新定位到該P(yáng)OS所在的位置,并把該位置附近的 BUFSIZE字節(jié)的文件內(nèi)容填充BUFFER,返回B。
下面給出關(guān)鍵部分代碼及其說明:
// boolean write(byte bw, long pos):向當(dāng)前文件POS位置寫入字節(jié)BW。
// 根據(jù)POS的不同及BUF的位置:存在修改、追加、BUF中、BUF外等情
況。在邏輯判斷時(shí),把最可能出現(xiàn)的情況,最先判斷,這樣可提高速度。
// fileendpos:指示當(dāng)前文件的尾偏移地址,主要考慮到追加因素
public boolean write(byte bw, long pos) throws IOException {
if ((pos >= this.bufstartpos) && (pos <= this.bufendpos)) {
// write pos in buf
this.buf[(int)(pos - this.bufstartpos)] = bw;
this.bufdirty = true;
if (pos == this.fileendpos + 1) { // write pos is append pos
this.fileendpos++;
this.bufusedsize++;
}
} else { // write pos not in buf
this.seek(pos);
if ((pos >= 0) && (pos <= this.fileendpos) && (this.fileendpos != 0))
{ // write pos is modify file
this.buf[(int)(pos - this.bufstartpos)] = bw;
} else if (((pos == 0) && (this.fileendpos == 0))
|| (pos == this.fileendpos + 1)) { // write pos is append pos
this.buf[0] = bw;
this.fileendpos++;
this.bufusedsize = 1;
} else {
throw new IndexOutOfBoundsException();
}
this.bufdirty = true;
}
this.curpos = pos;
return true;
}
至此緩沖寫基本實(shí)現(xiàn),逐字節(jié)COPY一個(gè)12兆的文件,(這里牽涉到讀和寫,結(jié)合緩沖讀,用BufferedRandomAccessFile試一下讀/寫的速度):
讀 | 寫 | 耗用時(shí)間(秒) |
RandomAccessFile | RandomAccessFile | 95.848 |
BufferedInputStream + DataInputStream | BufferedOutputStream + DataOutputStream | 2.935 |
BufferedRandomAccessFile | BufferedOutputStream + DataOutputStream | 2.813 |
BufferedRandomAccessFile | BufferedRandomAccessFile | 2.453 |
可見綜合讀/寫速度已超越BufferedInput/OutputStream+DataInput/OutputStream。
優(yōu)化BufferedRandomAccessFile。
優(yōu)化原則:
•調(diào)用頻繁的語句最需要優(yōu)化,且優(yōu)化的效果最明顯。
•多重嵌套邏輯判斷時(shí),最可能出現(xiàn)的判斷,應(yīng)放在最外層。
•減少不必要的NEW。
這里舉一典型的例子:
public void seek(long pos) throws IOException {
...
this.bufstartpos = pos * bufbitlen / bufbitlen;
// bufbitlen指buf[]的位長,例:若bufsize=1024,則bufbitlen=10。
...
}
seek函數(shù)使用在各函數(shù)中,調(diào)用非常頻繁,上面加重的這行語句根據(jù)pos和bufsize確定buf[]對(duì)應(yīng)當(dāng)前文件的映射位置,用"*"、"/"確定,顯然不是一個(gè)好方法。
優(yōu)化一:this.bufstartpos = (pos << bufbitlen) >> bufbitlen;
優(yōu)化二:this.bufstartpos = pos & bufmask; // this.bufmask = ~((long)this.bufsize - 1);
兩者效率都比原來好,但后者顯然更好,因?yàn)榍罢咝枰獌纱我莆贿\(yùn)算、后者只需一次邏輯與運(yùn)算(bufmask可以預(yù)先得出)。
至此優(yōu)化基本實(shí)現(xiàn),逐字節(jié)COPY一個(gè)12兆的文件,(這里牽涉到讀和寫,結(jié)合緩沖讀,用優(yōu)化后BufferedRandomAccessFile試一下讀/寫的速度):
讀 | 寫 | 耗用時(shí)間(秒) |
RandomAccessFile | RandomAccessFile | 95.848 |
BufferedInputStream + DataInputStream | BufferedOutputStream + DataOutputStream | 2.935 |
BufferedRandomAccessFile | BufferedOutputStream + DataOutputStream | 2.813 |
BufferedRandomAccessFile | BufferedRandomAccessFile | 2.453 |
BufferedRandomAccessFile優(yōu) | BufferedRandomAccessFile優(yōu) | 2.197 |
可見優(yōu)化盡管不明顯,還是比未優(yōu)化前快了一些,也許這種效果在老式機(jī)上會(huì)更明顯。
以上比較的是順序存取,即使是隨機(jī)存取,在絕大多數(shù)情況下也不止一個(gè)BYTE,所以緩沖機(jī)制依然有效。而一般的順序存取類要實(shí)現(xiàn)隨機(jī)存取就不怎么容易了。
需要完善的地方
提供文件追加功能:
public boolean append(byte bw) throws IOException {
return this.write(bw, this.fileendpos + 1);
}
提供文件當(dāng)前位置修改功能:
public boolean write(byte bw) throws IOException {
return this.write(bw, this.curpos);
}
返回文件長度(由于BUF讀寫的原因,與原來的RandomAccessFile類有所不同):
public long length() throws IOException {
return this.max(this.fileendpos + 1, this.initfilelen);
}
返回文件當(dāng)前指針(由于是通過BUF讀寫的原因,與原來的RandomAccessFile類有所不同):
public long getFilePointer() throws IOException {
return this.curpos;
}
提供對(duì)當(dāng)前位置的多個(gè)字節(jié)的緩沖寫功能:
public void write(byte b[], int off, int len) throws IOException {
long writeendpos = this.curpos + len - 1;
if (writeendpos <= this.bufendpos) { // b[] in cur buf
System.arraycopy(b, off, this.buf, (int)(this.curpos - this.bufstartpos),
len);
this.bufdirty = true;
this.bufusedsize = (int)(writeendpos - this.bufstartpos + 1);
} else { // b[] not in cur buf
super.seek(this.curpos);
super.write(b, off, len);
}
if (writeendpos > this.fileendpos)
this.fileendpos = writeendpos;
this.seek(writeendpos+1);
}
public void write(byte b[]) throws IOException {
this.write(b, 0, b.length);
}
提供對(duì)當(dāng)前位置的多個(gè)字節(jié)的緩沖讀功能:
public int read(byte b[], int off, int len) throws IOException {
long readendpos = this.curpos + len - 1;
if (readendpos <= this.bufendpos && readendpos <= this.fileendpos ) {
// read in buf
System.arraycopy(this.buf, (int)(this.curpos - this.bufstartpos),
b, off, len);
} else { // read b[] size > buf[]
if (readendpos > this.fileendpos) { // read b[] part in file
len = (int)(this.length() - this.curpos + 1);
}
super.seek(this.curpos);
len = super.read(b, off, len);
readendpos = this.curpos + len - 1;
}
this.seek(readendpos + 1);
return len;
}
public int read(byte b[]) throws IOException {
return this.read(b, 0, b.length);
}
public void setLength(long newLength) throws IOException {
if (newLength > 0) {
this.fileendpos = newLength - 1;
} else {
this.fileendpos = 0;
}
super.setLength(newLength);
}
public void close() throws IOException {
this.flushbuf();
super.close();
}
至此完善工作基本完成,試一下新增的多字節(jié)讀/寫功能,通過同時(shí)讀/寫1024個(gè)字節(jié),來COPY一個(gè)12兆的文件,(這里牽涉到讀和寫,用完善后BufferedRandomAccessFile試一下讀/寫的速度):
讀 | 寫 | 耗用時(shí)間(秒) |
RandomAccessFile | RandomAccessFile | 95.848 |
BufferedInputStream + DataInputStream | BufferedOutputStream + DataOutputStream | 2.935 |
BufferedRandomAccessFile | BufferedOutputStream + DataOutputStream | 2.813 |
BufferedRandomAccessFile | BufferedRandomAccessFile | 2.453 |
BufferedRandomAccessFile優(yōu) | BufferedRandomAccessFile優(yōu) | 2.197 |
BufferedRandomAccessFile完 | BufferedRandomAccessFile完 | 0.401 |
與JDK1.4新類MappedByteBuffer+RandomAccessFile的對(duì)比?
JDK1.4提供了NIO類 ,其中MappedByteBuffer類用于映射緩沖,也可以映射隨機(jī)文件訪問,可見JAVA設(shè)計(jì)者也看到了RandomAccessFile的問題,并加以改進(jìn)。怎么通過MappedByteBuffer+RandomAccessFile拷貝文件呢?下面就是測(cè)試程序的主要部分:
RandomAccessFile rafi = new RandomAccessFile(SrcFile, "r");
RandomAccessFile rafo = new RandomAccessFile(DesFile, "rw");
FileChannel fci = rafi.getChannel();
FileChannel fco = rafo.getChannel();
long size = fci.size();
MappedByteBuffer mbbi = fci.map(FileChannel.MapMode.READ_ONLY, 0, size);
MappedByteBuffer mbbo = fco.map(FileChannel.MapMode.READ_WRITE, 0, size);
long start = System.currentTimeMillis();
for (int i = 0; i < size; i++) {
byte b = mbbi.get(i);
mbbo.put(i, b);
}
fcin.close();
fcout.close();
rafi.close();
rafo.close();
System.out.println("Spend: "+(double)(System.currentTimeMillis()-start) / 1000 + "s");
試一下JDK1.4的映射緩沖讀/寫功能,逐字節(jié)COPY一個(gè)12兆的文件,(這里牽涉到讀和寫):
讀 | 寫 | 耗用時(shí)間(秒) |
RandomAccessFile | RandomAccessFile | 95.848 |
BufferedInputStream + DataInputStream | BufferedOutputStream + DataOutputStream | 2.935 |
BufferedRandomAccessFile | BufferedOutputStream + DataOutputStream | 2.813 |
BufferedRandomAccessFile | BufferedRandomAccessFile | 2.453 |
BufferedRandomAccessFile優(yōu) | BufferedRandomAccessFile優(yōu) | 2.197 |
BufferedRandomAccessFile完 | BufferedRandomAccessFile完 | 0.401 |
MappedByteBuffer+ RandomAccessFile | MappedByteBuffer+ RandomAccessFile | 1.209 |
確實(shí)不錯(cuò),看來JDK1.4比1.3有了極大的進(jìn)步。如果以后采用1.4版本開發(fā)軟件時(shí),需要對(duì)文件進(jìn)行隨機(jī)訪問,建議采用MappedByteBuffer+RandomAccessFile的方式。但鑒于目前采用JDK1.3及以前的版本開發(fā)的程序占絕大多數(shù)的實(shí)際情況,如果您開發(fā)的JAVA程序使用了RandomAccessFile類來隨機(jī)訪問文件,并因其性能不佳,而擔(dān)心遭用戶詬病,請(qǐng)?jiān)囉帽疚乃峁┑腂ufferedRandomAccessFile類,不必推翻重寫,只需IMPORT 本類,把所有的RandomAccessFile改為BufferedRandomAccessFile,您的程序的性能將得到極大的提升,您所要做的就這么簡單。
未來的考慮
讀者可在此基礎(chǔ)上建立多頁緩存及緩存淘汰機(jī)制,以應(yīng)付對(duì)隨機(jī)訪問強(qiáng)度大的應(yīng)用。
- RandomAccessFile簡介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
- Java中IO流 RandomAccessFile類實(shí)例詳解
- Java使用RandomAccessFile類對(duì)文件進(jìn)行讀寫
- Java RandomAccessFile 指定位置實(shí)現(xiàn)文件讀取與寫入
- Java RandomAccessFile的用法詳解
- java使用randomaccessfile在文件任意位置寫入數(shù)據(jù)
- Java的字符讀寫類CharArrayReader和CharArrayWriter使用示例
- Java核心編程之文件隨機(jī)讀寫類RandomAccessFile詳解
相關(guān)文章
Java實(shí)現(xiàn)CSV格式轉(zhuǎn)對(duì)象
csv全稱“Comma-Separated Values”,是一種逗號(hào)分隔值格式的文件,常用來存儲(chǔ)數(shù)據(jù)的純文本格式文件。本文將用Java語言實(shí)現(xiàn)CSV轉(zhuǎn)對(duì)象,需要的可以參考一下2022-06-06java實(shí)現(xiàn)客戶端向服務(wù)器發(fā)送文件
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)客戶端向服務(wù)器發(fā)送文件,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01Spring?Boot指標(biāo)監(jiān)控及日志管理示例詳解
Spring Boot Actuator可以幫助程序員監(jiān)控和管理SpringBoot應(yīng)用,比如健康檢查、內(nèi)存使用情況統(tǒng)計(jì)、線程使用情況統(tǒng)計(jì)等,這篇文章主要介紹了Spring?Boot指標(biāo)監(jiān)控及日志管理,需要的朋友可以參考下2023-11-11使用Mybatis如何實(shí)現(xiàn)多個(gè)控制條件查詢
這篇文章主要介紹了使用Mybatis如何實(shí)現(xiàn)多個(gè)控制條件查詢,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03Spring中的@ControllerAdvice三種用法詳解
這篇文章主要介紹了Spring中的@ControllerAdvice三種用法詳解,加了@ControllerAdvice的類為那些聲明了(@ExceptionHandler、@InitBinder或@ModelAttribute注解修飾的)方法的類而提供的<BR>專業(yè)化的@Component,以供多個(gè)Controller類所共享,需要的朋友可以參考下2024-01-01Java 內(nèi)存模型中的happen-before關(guān)系詳解
這篇文章主要為大家介紹了Java 內(nèi)存模型中的happen-before關(guān)系示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10