Summary of channel usage in Java

  • 2020-04-01 03:55:32
  • OfStack

This example summarizes the use of channels in Java. Share with you for your reference. Specific analysis is as follows:

1. Definition of Channel interface:


public interface Channel
{
  public boolean isOpen( );
  public void close( ) throws IOException;
}

2. Common types of channels:

FileChannel, SocketChannel, ServerSocketChannel, and DatagramChannel;
FileChannel is initialized by RandomAccessFile, FileInputStream, and getChannel() of FileOutputStream.


SocketChannel sc = SocketChannel.open();
sc.connect (new InetSocketAddress ("somehost", someport));
ServerSocketChannel ssc = ServerSocketChannel.open( );
ssc.socket().bind (new InetSocketAddress (somelocalport));
DatagramChannel dc = DatagramChannel.open();

3. The Scatter/Gather, must use ByteBuffer. AllocateDirect (100).


public interface ScatteringByteChannel extends ReadableByteChannel {
  public long read (ByteBuffer [] dsts) throws IOException;
  public long read (ByteBuffer [] dsts, int offset, int length) throws IOException;
}
public interface GatheringByteChannel extends WritableByteChannel {
  public long write(ByteBuffer[] srcs) throws IOException;
  public long write(ByteBuffer[] srcs, int offset, int length) throws IOException;
}

4. File lock is related to file, not channel. It can work on processes, not threads. Thread synchronization can be achieved through a memory-mapped file

5. Buffer = fileChannel. Map (fileChannel. Mapmode. READ_ONLY, 100, 200);

6.MappedByteBuffer are direct.load () loads the entire file into memory (the change method does not guarantee completion). Force () flush the data to the hard drive.

7. The DatagramChannel system automatically assigns ports to unbound ports. Connect () of the DatagramChannel guarantees that only packets with the specified source address will be accepted. In this case, you can use the normal read and write methods, including Scatter/Gather

I hope this article has been helpful to your Java programming.


Related articles: