O与NIO操作效率对比(网上的说法千篇一律,99%都是错的,没经过自己的验证,正确的解释如下)
-
复制文件的情况:
注意:Files.copy和传统IO代码基本一样,只是它开辟的缓冲区大小较大,为8192(基本是缓冲区开的越大越快,但是也吃内存)- 当缓冲区(<1024)和数据量比较小(<10KB)时,传统IO 最为高效
效率上:传统IO > channel.transferTo > Files.copy > NIO::channel.write - 其他情况:
效率上:channel.transferTo > Files.copy > 传统IO > NIO::channel.write
- 当缓冲区(<1024)和数据量比较小(<10KB)时,传统IO 最为高效
-
多线程共用同一个流追加数据的情况:“NIO”比“IO”效率高
- 多线程使用不同的流追加数据的情况:“NIO+锁”比“IO+锁”效率高
注意:这种情况必须枷锁,否则会引起数据混乱
package com.demo.test;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
public class FileChannelDemo {
private static void createFile(String path, long numKB) {
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(path);
bw = new BufferedWriter(fw);
for (long i = 0; i < numKB * 16 * 4; i++) {
for (int j = 0; j < 16; j++) {
String hex = Integer.toHexString(j);
bw.write(hex);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void copyByIO(String srcPath, String dstPath) {
byte[] buffer = new byte[bufferSize];
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(srcPath);
fos = new FileOutputStream(dstPath);
int len;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void copyByNIO(String srcPath, String dstPath) {
FileInputStream fis = null;
FileOutputStream fos = null;
FileChannel fisChannel = null;
FileChannel fosChannel = null;
ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize);
try {
fis = new FileInputStream(srcPath);
fos = new FileOutputStream(dstPath);
fisChannel = fis.getChannel();
fosChannel = fos.getChannel();
while (fisChannel.read(buffer) != -1) {
buffer.flip();
fosChannel.write(buffer);
buffer.clear();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fisChannel != null) {
try {
fisChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fosChannel != null) {
try {
fosChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void copyByNIOTransfer(String srcPath, String dstPath) {
FileInputStream fis = null;
FileOutputStream fos = null;
FileChannel fisChannel = null;
FileChannel fosChannel = null;
try {
fis = new FileInputStream(srcPath);
fos = new FileOutputStream(dstPath);
fisChannel = fis.getChannel();
fosChannel = fos.getChannel();
long len = fisChannel.transferTo(0, fisChannel.size(), fosChannel);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fisChannel != null) {
try {
fisChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fosChannel != null) {
try {
fosChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void copyByFiles(String srcPath, String dstPath) {
Path path = Paths.get(srcPath);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(dstPath);
/*
* private static final int BUFFER_SIZE = 8192;
* private static long copy(InputStream source, OutputStream sink) throws IOException
* {
* long nread = 0L;
* byte[] buf = new byte[BUFFER_SIZE];
* int n;
* while ((n = source.read(buf)) > 0) {
* sink.write(buf, 0, n);
* nread += n;
* }
* return nread;
* }
*/
long len = Files.copy(path, fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void multiThreadWriteIO(String path) {
FileOutputStream fos = null;
int num = 1000;
final CountDownLatch countDownLatch = new CountDownLatch(num);
try {
fos = new FileOutputStream(path);
final FileOutputStream thisFos = fos;
Thread[] threads = new Thread[num];
for (int i = 0; i < num; i++) {
final int index = i;
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
byte[] buffer = (index + ". " + (new Date()).toString() + " hello world!xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx welcome to Newland\r\n").getBytes();
try {
thisFos.write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
countDownLatch.countDown();
}
});
}
for (int i = 0; i < num; i++) {
threads[i].start();
}
countDownLatch.await();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void multiThreadWriteNIO(String path) {
FileOutputStream fos = null;
FileChannel fosChannel = null;
int num = 1000;
final CountDownLatch countDownLatch = new CountDownLatch(num);
try {
fos = new FileOutputStream(path);
fosChannel = fos.getChannel();
final FileChannel thisFosChannel = fosChannel;
for (int i = 0; i < num; i++) {
final int index = i;
new Thread(new Runnable() {
@Override
public void run() {
ByteBuffer buffer = ByteBuffer.wrap((index + ". " + (new Date()).toString() + " hello world!xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx welcome to Newland\r\n").getBytes());
try {
thisFosChannel.write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
countDownLatch.countDown();
}
}).start();
}
countDownLatch.await();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (fosChannel != null) {
try {
fosChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void multiThreadOpenWriteIO(final String path) {
int num = 1000;
final CountDownLatch countDownLatch = new CountDownLatch(num);
final Object obj = new Object();
for (int i = 0; i < num; i++) {
final int index = i;
new Thread(new Runnable() {
@Override
public void run() {
RandomAccessFile raf = null;
synchronized (obj) {
try {
raf = new RandomAccessFile(path, "rw");
raf.seek(raf.length());
byte[] buffer = (index + ". " + (new Date()).toString() + " hello world!xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx welcome to Newland\r\n").getBytes();
raf.write(buffer);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
countDownLatch.countDown();
}
}).start();
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void multiThreadOpenWriteNIO(final String path, long sleepTimeMillis) {
int num = 1000;
final CountDownLatch countDownLatch = new CountDownLatch(num);
for (int i = 0; i < num; i++) {
final int index = i;
new Thread(new Runnable() {
@Override
public void run() {
RandomAccessFile raf = null;
FileChannel rafChannel = null;
FileLock fl = null;
try {
raf = new RandomAccessFile(path, "rw");
rafChannel = raf.getChannel();
while (true) {
try {
fl = rafChannel.tryLock();
if (fl != null) {
break;
}
} catch (OverlappingFileLockException e) {
try {
Thread.sleep(sleepTimeMillis);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
rafChannel.position(rafChannel.size());
ByteBuffer buffer = ByteBuffer.wrap((index + ". " + (new Date()).toString() + " hello world!xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx welcome to Newland\r\n").getBytes());
rafChannel.write(buffer);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fl != null) {
try {
fl.release();
} catch (IOException e) {
e.printStackTrace();
}
}
if (rafChannel != null) {
try {
rafChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
countDownLatch.countDown();
}
}).start();
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static final int[] NUM_KB_ARR = { 1, 10, 100, 1024, 10 * 1024, 100 * 1024 };
private static final int[] BUFF_SIZE_ARR = { 256, 1024, 8192 };
private static int bufferSize = 8192;
private static long beginTime;
private static void calcCostTime(String msg) {
if (msg == null) {
beginTime = System.nanoTime();
} else {
System.out.println(msg + "\tcost\t" + String.format("%011d", System.nanoTime() - beginTime) + "us");
}
}
public static void main(String[] args) {
String testPath = "test.txt";
String ioOutputPath = "io.txt";
String nioOutputPath = "nio.txt";
String nioTransferOutputPath = "nioTransfer.txt";
String nioFilesPath = "nioFiles.txt";
String ioMultiThreadWritePath = "multiThreadIoWritePath.txt";
String nioMultiThreadNioWritePath = "multiThreadNioWritePath.txt";
String iomultiThreadIoOpenWritePath = "multiThreadIoOpenWritePath.txt";
String nioMultiThreadNioOpenWritePath = "multiThreadNioOpenWritePath.txt";
Runtime runtime = Runtime.getRuntime();
int availableProcessors = runtime.availableProcessors();
System.out.println("availableProcessors = " + availableProcessors);
System.out.println("vm's freeMemory = " + runtime.freeMemory() + ", vm's totalMemory = " + runtime.totalMemory());
System.out.println();
for (int i = 0; i < BUFF_SIZE_ARR.length; i++) {
bufferSize = BUFF_SIZE_ARR[i];
System.out.println("BUFF_SIZE = " + bufferSize);
// 复制文件的情况
for (int j = 0; j < NUM_KB_ARR.length; j++) {
System.out.println(j + ". FILE_SIZE = " + NUM_KB_ARR[j] + " KB");
String numKBStr = String.format("%09d", NUM_KB_ARR[j]);
calcCostTime(null);
createFile(testPath, NUM_KB_ARR[j]);
calcCostTime("createFile\t\t" + numKBStr);
calcCostTime(null);
copyByIO(testPath, bufferSize+"_"+ioOutputPath);
calcCostTime("copyByIO\t\t" + numKBStr);
calcCostTime(null);
copyByNIO(testPath, bufferSize+"_"+nioOutputPath);
calcCostTime("copyByNIO\t\t" + numKBStr);
calcCostTime(null);
copyByNIOTransfer(testPath, bufferSize+"_"+nioTransferOutputPath);
calcCostTime("copyByNIOTransfer\t" + numKBStr);
calcCostTime(null);
copyByFiles(testPath, bufferSize+"_"+nioFilesPath);
calcCostTime("copyByFiles\t\t" + numKBStr);
}
System.out.println();
}
// 多线程共用同一个流追加数据的情况
calcCostTime(null);
multiThreadWriteIO(ioMultiThreadWritePath);
calcCostTime("multiThreadWriteIO\t\t");
calcCostTime(null);
multiThreadWriteNIO(nioMultiThreadNioWritePath);
calcCostTime("multiThreadWriteNIO\t\t");
// 多线程使用不同的流追加数据的情况
calcCostTime(null);
multiThreadOpenWriteIO(iomultiThreadIoOpenWritePath);
calcCostTime("multiThreadOpenWriteIO\t\t");
calcCostTime(null);
multiThreadOpenWriteNIO(nioMultiThreadNioOpenWritePath, 15);
calcCostTime("multiThreadOpenWriteNIO\t\t");
System.out.println();
File file = new File(".");
for (String path : file.list()) {
if (path.endsWith(".txt")) {
try {
System.out.println("prepare delete "+path);
Files.delete(Paths.get(path));
System.out.println("delete succ");
} catch (IOException e) {
e.printStackTrace();
System.out.println("delete fail");
}
}
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
- 285
- 286
- 287
- 288
- 289
- 290
- 291
- 292
- 293
- 294
- 295
- 296
- 297
- 298
- 299
- 300
- 301
- 302
- 303
- 304
- 305
- 306
- 307
- 308
- 309
- 310
- 311
- 312
- 313
- 314
- 315
- 316
- 317
- 318
- 319
- 320
- 321
- 322
- 323
- 324
- 325
- 326
- 327
- 328
- 329
- 330
- 331
- 332
- 333
- 334
- 335
- 336
- 337
- 338
- 339
- 340
- 341
- 342
- 343
- 344
- 345
- 346
- 347
- 348
- 349
- 350
- 351
- 352
- 353
- 354
- 355
- 356
- 357
- 358
- 359
- 360
- 361
- 362
- 363
- 364
- 365
- 366
- 367
- 368
- 369
- 370
- 371
- 372
- 373
- 374
- 375
- 376
- 377
- 378
- 379
- 380
- 381
- 382
- 383
- 384
- 385
- 386
- 387
- 388
- 389
- 390
- 391
- 392
- 393
- 394
- 395
- 396
- 397
- 398
- 399
- 400
- 401
- 402
- 403
- 404
- 405
- 406
- 407
- 408
- 409
- 410
- 411
- 412
- 413
- 414
- 415
- 416
- 417
- 418
- 419
- 420
- 421
- 422
- 423
- 424
- 425
- 426
- 427
- 428
- 429
- 430
- 431
- 432
- 433
- 434
- 435
- 436
- 437
- 438
- 439
- 440
- 441
- 442
- 443
- 444
- 445
- 446
- 447
- 448
- 449
- 450
- 451
- 452
- 453
- 454
- 455
- 456
- 457
- 458
- 459
- 460
- 461
- 462
- 463
- 464
- 465
- 466
- 467
- 468
- 469
- 470
- 471
- 472
- 473
- 474
- 475
- 476
- 477
- 478
- 479
- 480
- 481
- 482
- 483
- 484
- 485
- 486
- 487
- 488
- 489
- 490
- 491
- 492
- 493
- 494
- 495
- 496
- 497
- 498
- 499
- 500
- 501
- 502
- 503
- 504
- 505
- 506
- 507
- 508
- 509
注意到:在“多线程使用不同的流追加数据”的情况下,“NIO+锁”每次循环都需要休眠一定时间再判断是否可以成功获得锁。因此继续修改代码来测试这个最优时间。
结论:可以看出,在休眠时间为15ms的时候所消耗的时间最少,效率最高。
(这里需要根据具体问题具体分析,和很多环境因素都有关,没有定论)
//(变量、函数定义,略……)
public satic void main(String[] args) {
for(int i=0;i<SLEEP_TIME_MILLIS_ARR.length; i++) {
calcCostTime(null);
multiThreadOpenWriteNIO(SLEEP_TIME_MILLIS_ARR[i] + "_" + nioMultiThreadNioOpenWritePath, SLEEP_TIME_MILLIS_ARR[i]);
calcCostTime("multiThreadOpenWriteNIO\t" + SLEEP_TIME_MILLIS_ARR[i] + "\t");
System.out.println();
}
//(删除文件部分,略……)
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
通过轮询,然后不断尝试无形中浪费了很多时间。后面我想:是否可以走“事件-通知”的模式,即“wait-notify”,来提高执行效率呢?
很不幸,结论是否定的。因为多线程只能通过“wait-notify”来暂停和唤醒,而“wait-notify”又必须引入同步锁,同步锁增加了程序的开销。
记得《Java并发编程》中大意是这么说的:“同步代码块会强制跨越内存栅栏(强制将寄存器中的数据更新到主存中)……引入锁会带来跟多的开销,并且容易引起不必要的错误,因此能不用锁尽量不用锁”。
//(变量、函数定义,略……)
private static void multiThreadOpenWriteNIOEx(final String path) {
int num = 1000;
final CountDownLatch countDownLatch = new CountDownLatch(num);
final Object object = new Object();
for (int i = 0; i < num; i++) {
final int index = i;
new Thread(new Runnable() {
@Override
public void run() {
RandomAccessFile raf = null;
FileChannel rafChannel = null;
FileLock fl = null;
try {
raf = new RandomAccessFile(path, "rw");
rafChannel = raf.getChannel();
if( index != 0) {
synchronized (object) {
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
while(true) {
try {
fl = rafChannel.tryLock();
if(fl != null) {
break;
}
} catch (OverlappingFileLockException e) {
e.printStackTrace();
return;
}
}
rafChannel.position(rafChannel.size());
ByteBuffer buffer = ByteBuffer.wrap((index + ". " + (new Date()).toString() + " hello world!xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx welcome to Newland\r\n").getBytes());
rafChannel.write(buffer);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fl != null) {
try {
fl.release();
} catch (IOException e) {
e.printStackTrace();
}
}
if (rafChannel != null) {
try {
rafChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
synchronized (object) {
object.notify();
}
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
countDownLatch.countDown();
}
}).start();
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//(执行其它函数代码,略……)
calcCostTime(null);
multiThreadOpenWriteNIOEx(nioMultiThreadNioOpenWriteExPath);
calcCostTime("multiThreadOpenWriteNIOEx\t");
System.out.println();
//(删除文件部分,略……)
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88