Learning javanio-File Memory ing

Source: Internet
Author: User
Learning javanio-File Memory ing
    Blog type:
  • Java-NiO
I recently read the file memory ing. In NiO, it is easy to use.
After the file is mapped to memory, the access speed is naturally improved.
Of course there are also many problems. Now let's take a look at the memory ing file in NIO.

Java code
  1. Public abstract class filechannel extends
  2. Abstractchannel implements bytechannel, gatheringbytechannel, scatteringbytechannel {
  3. // This is a partial API listing
  4. Public abstract mappedbytebuffer map (mapmode mode, long position, Long SIZE)
  5. Public static class mapmode {
  6. Public static final mapmode read_only
  7. Public static final mapmode read_write
  8. Public static final mapmode private
  9. }
  10. }
Public abstract class filechannel extends actchannel implements bytechannel, gatheringbytechannel, scatteringbytechannel {// This is a partial API listingpublic abstract mappedbytebuffer map (mapmode mode, long position, Long SIZE) public static class mapmode {public static final mapmode read_only public static final mapmode read_write public static final mapmode private }}

The memory ing file is completed through a filechannel. The returned mappedbytebuffer is also a bytebuffer. There are three ing modes. This article focuses on the differences between the three ing modes.

Based on the map function, we know that we can map some files or all of them.
If the request size exceeds the file size, the file will grow accordingly to map. If it is integer. max_value, the file will reach 2.1 GB.
Of course, if you only request a read-only file and your size exceeds the file size, an ioexception will be thrown.
For the first two types of mapmode, read_only and read_write are well understood. Note that if read_write is used on a read-only file, a nonwritablechannelexception is thrown.
Mapmode. Private mode is very interesting. It is called the copy ing of copy-on-write. This is a common technology in the operating system. For example, when a child process is created, the child process shares the address space of the parent process. When the child process modifies the space, the child process copies the part to be modified. For private mode, the object will be copied only when the put function is used. It is possible to copy one or more pages. If there are other mappings at this time, you cannot see the changes after this put operation. That is, Private.

Note that there is no unmap function. That is to say, once the map is successful, the fileing still exists even if the filechannel is closed. Only when the edbytebuffer memory corresponding to the ing is recycled will the ing be canceled.

Mappedbytebuffer directly reflects the disk file. If the structure or size of the disk file changes, the file may not be accessible.
Mappedbytebuffer directly accesses the memory and does not occupy the VM memory.
Mappedbytebuffer is also a bytebuffer, so it can be used for reading and writing channels such as socketchannel.
There are several functions available for mappedbytebuffer. Java code

  1. Public abstract class mappedbytebuffer extends bytebuffer {
  2. // This is a partial API listing
  3. Public final mappedbytebuffer load ()
  4. Public final Boolean isloaded ()
  5. Public final mappedbytebuffer force ()
  6. }
Public abstract class mappedbytebuffer extends bytebuffer {// This is a partial API listing public final mappedbytebuffer load () Public final Boolean isloaded () Public final mappedbytebuffer force ()}

The load function is used to load files from the disk to the memory. This operation will cause a large number of system calls. Use it with caution. Once the file is loaded, accessing the file again is as fast as accessing the memory. However, these operations depend on the underlying calls of the operating system.

The isloaded function is used to determine whether the file is fully loaded into the memory.

Force forcibly synchronizes memory files to the disk. That is, apply the changes in mappedbytebuffer to the disk. This includes the metadata of the file (the last access, author, and creation time ). Of course, it does not work if it is in read_only or private mode.

In the following example, a memory ing file is used to generate an HTTP Response format file. Let's take a look at this example: Java code

  1. Package shaoxin. Nio;
  2. Import java. Io. fileinputstream;
  3. Import java. Io. fileoutputstream;
  4. Import java. Io. ioexception;
  5. Import java.net. urlconnection;
  6. Import java. NiO. bytebuffer;
  7. Import java. NiO. mappedbytebuffer;
  8. Import java. NiO. channels. filechannel;
  9. Import java. NiO. channels. filechannel. mapmode;
  10. /***
  11. * Dummy HTTP server using mappedbytebuffer.
  12. * Given a filename on the command line, pretend to be
  13. * A Web server and generate an HTTP Response containing
  14. * The File Content preceded by appropriate headers
  15. * Data is send with a gathering write.
  16. *
  17. * @ Author Ron Hitchens (ron@ronsoft.com)
  18. *
  19. */
  20. Public class mappedhttp {
  21. Private Static final string output_file = "mappedhttp. Out ";
  22. Private Static final string line_sep = "\ r \ n ";
  23. Private Static final string server_id = "server: ronsoft dummy server ";
  24. Private Static final string http_hdr =
  25. "HTTP/1.0 200 OK" + line_sep + server_id + line_sep;
  26. Private Static final string http_404_hdr =
  27. "HTTP/1.0 404 Not Found" + line_sep + server_id + line_sep;
  28. Private Static final string msg_404 = "cound not open file :";
  29. Public static void main (string [] ARGs) throws exception {
  30. If (ARGs. Length <1 ){
  31. System. Err. println ("Usage: FILENAME ");
  32. Return;
  33. }
  34. String file = ARGs [0];
  35. Bytebuffer header = bytebuffer. Wrap (bytes (http_hdr ));
  36. Bytebuffer dynhdrs = bytebuffer. Allocate (128 );
  37. Bytebuffer [] Gather = {header, dynhdrs, null };
  38. String contenttype = "Unknown/unknown ";
  39. Long contentlength =-1;
  40. Try {
  41. Fileinputstream FCM = new fileinputstream (File );
  42. Filechannel fc = FCM. getchannel ();
  43. Mappedbytebuffer filedata =
  44. FC. Map (mapmode. read_only, 0, FC. Size ());
  45. Gather [2] = filedata;
  46. Contentlength = FC. Size ();
  47. Contenttype = urlconnection. guesscontenttypefromname (File );
  48. } Catch (ioexception e ){
  49. // File cocould not be opend; Report Problem
  50. Bytebuffer Buf = bytebuffer. Allocate (128 );
  51. String MSG = msg_404 + line_sep;
  52. Buf. Put (bytes (MSG ));
  53. Buf. Flip ();
  54. // Use the HTTP Error Response
  55. Gather [0] = bytebuffer. Wrap (bytes (http_404_hdr ));
  56. Gather [2] = Buf;
  57. Contentlength = MSG. Length ();
  58. Contenttype = "text/plain ";
  59. }
  60. Stringbuffer sb = new stringbuffer ();
  61. SB. append ("Content-Length:" + contentlength );
  62. SB. append (line_sep );
  63. SB. append ("Content-Type:"). append (contenttype );
  64. SB. append (line_sep). append (line_sep );
  65. Dynhdrs. Put (bytes (sb. tostring ()));
  66. Dynhdrs. Flip ();
  67. Fileoutputstream Fos = new fileoutputstream (output_file );
  68. Filechannel out = FOS. getchannel ();
  69. // All the buffers have been prepared, write them out
  70. While (Out. Write (gather)> 0 ){
  71. // Empty body; loop until all buffers are empty
  72. }
  73. Out. Close ();
  74. System. Out. println ("output written to" + output_file );
  75. }
  76. // Convert a string to its constituent bytes
  77. // From the ASCII character set
  78. Private Static byte [] bytes (string) throws exception {
  79. Return (string. getbytes ("US-ASCII "));
  80. }
  81. }

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.