Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
неблокируемость, что означает способность к параллельному выполнению операций ввода-вывода и вычислений
Classic IO (буфферизированная запись BufferedOutputsteam 1M)
/tmp/test-classicio-3968394580096440112.tmp took 7994.238 ms
Mapped file of FileChannel
/tmp/test-channel-3465783895111396195.tmp took 16993.815 ms
1M Direct ByteBuffer с последующим копированием в FileChannel
/tmp/test-channel-bb-3779212028599883329.tmp took 21364.169 ms
1M Heap ByteBuffer с последующим копированием в FileChannel
/tmp/test-channel-heap-bb-3642623955892374473.tmp took 23544.936 ms
package asyncexample1;
import java.nio.*;
import java.nio.channels.*;
import java.nio.file.*;
import java.util.concurrent.Future;
import static java.nio.file.StandardOpenOption.*;
public class AsyncExample1 {
private static long startSync, stopSync, stopAsync, filePosition;
private static String writePath = «C:\\tmp\\tmp1.txt»;
private static int bufferSize = 1024*1024;
public static void main(String[] args)
{
//---------- Initializing parameters —
ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
filePosition = 0;
startSync = stopSync = stopAsync = 0;
//---------- Initializing buffer —
int n = buffer.limit();
byte[] data = new byte[n];
for ( int i=0; i<n; i++ ) { data[i] = '*'; }
buffer.put(data);
buffer.flip();
//---------- Create file channel — // Note this operation is outside of time measurement interval
Path path = Paths.get(writePath);
try ( AsynchronousFileChannel writeChannel =
AsynchronousFileChannel.open( path, CREATE, WRITE ); )
{
//---------- Send write request, first interval —
startSync = System.nanoTime();
Future operation = writeChannel.write( buffer, filePosition );
stopSync = System.nanoTime();
//---------- Wait for request execution, second interval — while( !operation.isDone() );
stopAsync = System.nanoTime();
//---------- Exception handling —
} catch (Exception e) { System.out.println( «Error: » + e ); }
//---------- Visual timings results —
printInterval( startSync, stopSync, «Send task» );
printInterval( stopSync, stopAsync, «Execute task»);
}
//---------- Helper method for output results to console — // t1 = start interval time moment, nanoseconds
// t2 = end interval time moment, nanoseconds
// s1 = parameter name string for print
private static void printInterval( long t1, long t2, String s1 )
{
double x = t2-t1;
String s2 = «error, »;
if (x<0) { s2 = s2 + «negative time interval»; }
if (x==0) { s2 = s2 + «too small time»; }
if (x>0)
{
x /= 1000000;
s2 = String.format("%.6f ms", x);
}
System.out.println( s1 + " = " + s2 );
}
//---------- End of main class —
}

NIO: между Сциллой и Харибдой?