Summary of channel usage in Java _java

Source: Internet
Author: User

This article summarizes the channel usage in Java. Share to everyone for your reference. The specific analysis is as follows:

Definition of 1.Channel interface:

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

Common Types of 2.Channel:

FileChannel, Socketchannel, Serversocketchannel, and Datagramchannel;
FileChannel are initialized by Randomaccessfile, FileInputStream, FileOutputStream Getchannel ().

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.scatter/gather, must use Bytebuffer.allocatedirect (100)

Public interface Scatteringbytechannel extends Readablebytechannel {public
  long read (Bytebuffer [] dsts) throws Ioex ception;
  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 associated with file, not channel. Can be valid for a process, not a thread. Thread synchronization can be implemented through a memory-mapped file (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 modification method is not guaranteed to be completed). Force () flush the data to the hard disk.

7. The Datagramchannel system for unbound ports automatically assigns ports. Datagramchannel Connect (), which guarantees that only packets with the specified source address will be accepted. At this point, you can use the normal read and write methods, including Scatter/gather

I hope this article will help you with your Java programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.