Learning javanio-File Memory ing
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
- Public abstract class filechannel extends
- Abstractchannel implements bytechannel, gatheringbytechannel, scatteringbytechannel {
- // This is a partial API listing
- Public 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
- }
- }
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
- Public abstract class mappedbytebuffer extends bytebuffer {
- // This is a partial API listing
- Public final mappedbytebuffer load ()
- Public final Boolean isloaded ()
- Public final mappedbytebuffer force ()
- }
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
- Package shaoxin. Nio;
- Import java. Io. fileinputstream;
- Import java. Io. fileoutputstream;
- Import java. Io. ioexception;
- Import java.net. urlconnection;
- Import java. NiO. bytebuffer;
- Import java. NiO. mappedbytebuffer;
- Import java. NiO. channels. filechannel;
- Import java. NiO. channels. filechannel. mapmode;
- /***
- * Dummy HTTP server using mappedbytebuffer.
- * Given a filename on the command line, pretend to be
- * A Web server and generate an HTTP Response containing
- * The File Content preceded by appropriate headers
- * Data is send with a gathering write.
- *
- * @ Author Ron Hitchens (ron@ronsoft.com)
- *
- */
- Public class mappedhttp {
- Private Static final string output_file = "mappedhttp. Out ";
- Private Static final string line_sep = "\ r \ n ";
- Private Static final string server_id = "server: ronsoft dummy server ";
- Private Static final string http_hdr =
- "HTTP/1.0 200 OK" + line_sep + server_id + line_sep;
- Private Static final string http_404_hdr =
- "HTTP/1.0 404 Not Found" + line_sep + server_id + line_sep;
- Private Static final string msg_404 = "cound not open file :";
- Public static void main (string [] ARGs) throws exception {
- If (ARGs. Length <1 ){
- System. Err. println ("Usage: FILENAME ");
- Return;
- }
- String file = ARGs [0];
- Bytebuffer header = bytebuffer. Wrap (bytes (http_hdr ));
- Bytebuffer dynhdrs = bytebuffer. Allocate (128 );
- Bytebuffer [] Gather = {header, dynhdrs, null };
- String contenttype = "Unknown/unknown ";
- Long contentlength =-1;
- Try {
- Fileinputstream FCM = new fileinputstream (File );
- Filechannel fc = FCM. getchannel ();
- Mappedbytebuffer filedata =
- FC. Map (mapmode. read_only, 0, FC. Size ());
- Gather [2] = filedata;
- Contentlength = FC. Size ();
- Contenttype = urlconnection. guesscontenttypefromname (File );
- } Catch (ioexception e ){
- // File cocould not be opend; Report Problem
- Bytebuffer Buf = bytebuffer. Allocate (128 );
- String MSG = msg_404 + line_sep;
- Buf. Put (bytes (MSG ));
- Buf. Flip ();
- // Use the HTTP Error Response
- Gather [0] = bytebuffer. Wrap (bytes (http_404_hdr ));
- Gather [2] = Buf;
- Contentlength = MSG. Length ();
- Contenttype = "text/plain ";
- }
- Stringbuffer sb = new stringbuffer ();
- SB. append ("Content-Length:" + contentlength );
- SB. append (line_sep );
- SB. append ("Content-Type:"). append (contenttype );
- SB. append (line_sep). append (line_sep );
- Dynhdrs. Put (bytes (sb. tostring ()));
- Dynhdrs. Flip ();
- Fileoutputstream Fos = new fileoutputstream (output_file );
- Filechannel out = FOS. getchannel ();
- // All the buffers have been prepared, write them out
- While (Out. Write (gather)> 0 ){
- // Empty body; loop until all buffers are empty
- }
- Out. Close ();
- System. Out. println ("output written to" + output_file );
- }
- // Convert a string to its constituent bytes
- // From the ASCII character set
- Private Static byte [] bytes (string) throws exception {
- Return (string. getbytes ("US-ASCII "));
- }
- }