This article is from my personal blog: Java NIO channel (ii)
One, File Channel
The file channel is always blocked and therefore cannot be placed in a non-clogging mode.
The FileChannel object is thread-safe. Multiple processes can invoke methods concurrently on the same instance without causing any problems, but not all operations are multithreaded. Actions that affect the channel location or affect the file size are single-threaded.
The view of a file seen through an FileChannel instance may or may not be consistent with the view of the file seen through an external non-Java process.
To create a file channel:
Randomaccessfile randomaccessfile = new Randomaccessfile (filename, "R");//Set the location of the read file Randomaccessfile.seek (1000);// Create file channel FileChannel FileChannel = Randomaccessfile.getchannel (); System.out.println (Filechannel.position ()); Print 1000randomaccessfile.seek (500); System.out.println (Filechannel.position ()); Print 500filechannel.position (200); System.out.println (Randomaccessfile.getfilepointer ()); Print 200
Second, file lock (Filelock)
As we all know, file locks are divided into exclusive and shared locks. An exclusive lock is when a lock has the permission to operate the file, and the other visitors must wait for the current operator to complete the ability to manipulate the file, while the shared lock is all the visitors can use the file at the same time.
Exclusive locks are most important for file writes, while shared locks are used for file reads.
The Java file lock is only associated with the file, not the channel. File locks are designed to provide access to documents at the process level, for example, between basic program components or when inheriting components from other vendors. Suppose you need to control concurrent access to multiple Java threads. You need to do a locking scheme for yourself.
There are four methods for requesting locks in the FileChannel class, respectively:
Public final Filelock Lock ();p ublic abstract Filelock Lock (long position, long size, Boolean shared);p ublic final Filelock Trylock ();p ublic abstract Filelock trylock (long position, long Size,boolean shared);
The two-parameter request method means specifying the region location where the file needs to be locked, and setting whether the lock is a shared lock, and Note that if an exclusive lock is requested, the file must be open in write mode, and the size value of the lock area can exceed the tail of the file. This allows you to lock down the file data regions that need to be written in advance, and to lock a file content area that does not include whatever content. the request method without parameters is to request an exclusive lock on the entire file, that is, a lock obtained by using the non-parameter request method, which will clog up the subsequent operation only if the locked-in caller runs its operation.
Be sure to remember that after the operation is complete. Be sure to release the lock, or it may cause the program to crash or deadlock phenomenon.
Three, memory-mapped files (mappedbytebuffer file):
The FileChannel class provides a method named map () that establishes a virtual memory mapping mappedbytebuffer between an open file and a special type of bytebuffer. This object is similar to a memory-based buffer. Only the data elements of the object are stored in a file on disk. Calling the Get () method fetches the data from the disk file, which reflects the current contents of the file. Even after the mapping is established, the file has been changed by an external process. Also synchronizes to the memory view in which the object resides, and of course the put () method of the object also updates the file on this article synchronously. That is, changes to the file are also visible to other visitors.
Access to a file through a memory-mapping mechanism is much more efficient than reading and writing using conventional methods. is even more efficient than using channels. Because there is no need to make a clear system call. That can be very time consuming, and more importantly, the operating system's virtual memory can proactively cache memory pages. These memory pages are cached by the system memory, so the Java Virtual Machine memory heap is not consumed.
( Note: This paragraph is related to the operating system's memory mechanism, bloggers do not understand.) The blogger's idea is only to know that using this object will leave the JVM's memory heap. Removed the middle Bridge of the JVM).
public abstract mappedbytebuffer map (MapMode mode, long position, long size);p Ublic static class mapmode{ public static final mapmode read_only; public static final mapmode read_write; //represents the need for a copy-on-write mapping.
means that whatever changes you make through the put () method will result in a private copy of the data and //the data in that copy to be seen only by Mappedbytebuffer instances. This process does not make any changes to the dungeon file. And once the buffer //area is dragged to the garbage collection action. The data for those changes will be lost. When this mode is used. Other user changes to the file. can also reflect //to this memory-mapped area. Unless the buffer has changed the same area on the file.
public static final mapmode private;}
The first parameter of this method is to set whether the memory-mapped area is read-only or write-only or private, and the second and third parameters determine the area of the memory map. Note that this memory-mapped lock mode is not the same as the scope mechanism for file locks. assume that the value of size for this memory-mapped object is set to Integer.max_value. The size of this file will expand to more than 2.1GB. Other words. The lock area of this memory-mapped file is assumed to be beyond the size of the file, and it will voluntarily add data to the set area itself.
Once the Mappedbytebuffer object is created, it is not affected by the close of the channel, that is, assuming that closing the associated FileChannel does not break the map, only the drop buffer object itself destroys the mapping.
The Mappedbytebuffer class has several unique methods:
Public final Mappedbytebuffer load ();p ublic final Boolean isLoaded ();p ublic final Mappedbytebuffer force ();
When a virtual memory mapping is established for a file, the file data is typically not read from disk to memory (depending on the operating system).
The procedure is similar to opening a file: The file is positioned first, and then a file handle is created. When you're ready, you'll be able to access file data through a handle.
For map buffers. The virtual memory system will read the data in the corresponding chunks in the file according to the need.
This page verification or error-proof process takes a certain amount of time, because reading the file data into memory requires one or more disk access.
The load () method loads the entire file so that it resides in memory. However, calling this method is a costly operation. Because it causes a large number of pages to be paged in.
The Force () method forces changes on the mapping buffer to be applied to the persistent disk storage.
import java.io.file;import java.io.fileinputstream;import java.io.ioexception;import java.io.randomaccessfile;import java.nio.bytebuffer;import java.nio.mappedbytebuffer;import java.nio.channels.filechannel;import java.nio.channels.filechannel.mapmode;public class testmappedbyte {/** * @param args * @throws ioexception */public static void main (String[] args) throws ioexception { file file = new file ("/home/lifeix/3.txt"); if (! File.exists ()) { File.createnewfile (); } String str = "Jiang fuqiang is cool"; //This class has no Append file option. Suppose you need to append. You need to call the Fos.seek (int) method RandomAccessFile fos = new Randomaccessfile (file, "RWS"); filechannel fc = fos.getchannel (); bytebuffer bb = Bytebuffer.allocatedirect (Str.length ()); bb.put (Str.getBytes ()) ; bb.flip (); Fc.write (BB); bb.clear (); //assumes that fc.position () is not used here, the data written here overwrites the data written above, This is a way of appending files to your own implementation. //here can not use FileOutputStream, or will error mappedbytebuffer mbb = fc.map (Mapmode.read_write, fc.position (), (    &NBSP);; mbb.put (Str.getbytes ()); mbb.force (); mbb.clear (); fc.close (); fos.close (); FileInputStream fis = new FileInputStream (file); filechannel fc1 = Fis.getchannel (); mappedbytebuffer mbb1 = Fc1.map (Mapmode.read_only, 0, fc1.size ()); byte[] b = new byte[mbb1.remaining ()]; mbb1.get (b ); system.out.println (new string (b)); fc1.close (); fis.close (); }}
Java NIO Channel (ii)