Thinking logic of computer programs (61) and thinking 61
This section describes the memory ing file. The memory ing file is not a concept introduced by Java, but a function provided by the operating system, which is supported by most operating systems.
First, we will introduce the basic concepts of memory ing files, what is it, what problems can be solved, and then we will introduce how to use it in Java, we will design and implement a simple, persistent, cross-program message queue to demonstrate the application of memory ing files.
Basic Concepts
The memory ing file maps the file to the memory. The file corresponds to a byte array in the memory, and the operations on the file are changed to operations on the byte array, the operations on Byte arrays are directly mapped to files. This ing can be used to map all the regions of the file, or to map only some regions.
However, this ing is an illusion provided by the operating system. Files are generally not immediately loaded into the memory. The operating system only records this. When reading and writing occurs, load as needed. The operating system is usually loaded by page. A page can be understood as a piece. The page size is related to the operating system and hardware. The typical configuration may be 4 K or 8 K, when the operating system finds that the read/write area is not in the memory, it loads a page corresponding to the area to the memory.
This on-demand loading method makes it easy for memory ing files to process very large files. It does not matter if the memory cannot store the entire file. The operating system will automatically process the files and read the required content to the memory, save the modified content to the hard disk and release the memory that is no longer in use.
When an application writes data, it writes an array of bytes in the memory. When will this content be synchronized to the file? The timing is uncertain, determined by the operating system. However, as long as the operating system does not crash, the operating system will ensure synchronization to the file even if the application mapped to the file has exited.
In normal file reads and writes, there will be two copies of data, one from the hard disk to the operating system kernel, and the other from the operating system kernel to the user State application. In Memory ing files, there is usually only one copy, and the memory is allocated to the operating system kernel. applications access the operating system kernel memory space, this is obviously more efficient than normal reading and writing.
Another important feature of the memory ing file is that it can be shared by multiple different applications. Multiple programs can map the same file to the same memory area, A program's memory modification can be seen by other programs, which makes it particularly suitable for communication between different applications.
The operating system usually uses memory ing files when loading executable files, for example:
- Load the code as needed. Only the code currently running is in the memory, and other codes temporarily unavailable are still on the hard disk.
- The same executable file is started multiple times, and the file code has only one copy in the memory.
- The dynamic link library code shared by different applications only has one copy in the memory.
Memory ing files also have limitations. For example, it is not suitable for processing small files. It allocates memory by page, which wastes space for small files. In addition, the ing file consumes a certain amount of operating system resources, and Initialization is slow.
In summary, memory ing files are not required for reading and writing General files. However, if large files are processed, high read and write efficiency is required, such as the database system, or you need to share and communicate between different programs, you can consider the memory ing file.
After understanding the basic concepts of the memory ing file, let's look at how to use it in Java.
Usage
Ing File
The memory ing files must use FileInputStream/FileOutputStream or RandomAccessFile. They all have one method:
public FileChannel getChannel()
FileChannel has the following methods:
public MappedByteBuffer map(MapMode mode, long position, long size) throws IOException
The map method maps the current file to the memory. The ing result is a MappedByteBuffer object, which represents the byte array in the memory. Let's take a look at it later. Map has three parameters: mode indicates the ing mode, positon indicates the starting position of the ing, and size indicates the length.
Mode has three values:
- MapMode. READ_ONLY: Read-Only
- MapMode. READ_WRITE: both read and write
- MapMode. PRIVATE: PRIVATE mode. changes are not reflected in files or seen by other programs.
This mode is limited by the stream or RandomAccessFile behind it. For example, for FileInputStream or RandomAccessFile but the open mode is "r", the mode cannot be set to MapMode. READ_WRITE; otherwise, an exception is thrown.
If the mapped area exceeds the range of the existing file, the file is automatically extended and the expanded area byte content is 0.
After the ing is completed, the file can be closed, and subsequent File Read and Write can be done through MappedByteBuffer.
For example, to map the file "abc. dat" in read/write mode, the code can be:
RandomAccessFile file = new RandomAccessFile ("abc. dat "," rw "); try {MappedByteBuffer buf = file. getChannel (). map (MapMode. READ_WRITE, 0, file. length (); // use buf ...} catch (IOException e) {e. printStackTrace ();} finally {file. close ();}
MappedByteBuffer
How to Use MappedByteBuffer? It is a subclass of ByteBuffer, and ByteBuffer is a subclass of Buffer. ByteBuffer and Buffer are not only provided for memory ing files. They are a method for operating data in Java NIO. They are used in many places and there are many methods, we will only introduce some of the main related topics.
ByteBuffer can be simply understood as encapsulating a byte array. The length of this byte array is unchangeable. In the memory ing file, this length is determined by the parameter size in the map method.
ByteBuffer has a basic attribute position, which indicates the current read/write position. This position can be changed by the following methods:
// Obtain the current read/write position public final int position () // modify the current read/write position public final Buffer position (int newPosition)
There are many methods to read and write data based on the current location in ByteBuffer, such:
// Obtain a public abstract byte get () from the current location; // copy dst from the current location. length byte to dstpublic ByteBuffer get (byte [] dst) // read an intpublic abstract int getInt () from the current position (); // read a doublepublic abstract double getDouble () from the current position; // write the byte array src to the current position public final ByteBuffer put (byte [] src) // write the value of the long type to the current position public abstract ByteBuffer putLong (long value );
After reading and writing these methods, the position is automatically added.
There is also a set of methods that correspond to these methods. You can directly specify the position in the parameter, for example:
// Read an intpublic abstract int getInt (int index) from the index; // read a doublepublic abstract double getDouble (int index) from the index ); // write a doublepublic abstract ByteBuffer putDouble (int index, double value) in the index; // write a longpublic abstract ByteBuffer putLong (int index, long value) in the index );
These methods do not change the position of the current read/write position.
MappedByteBuffer also defines some methods:
// Check whether the file content is actually loaded into the memory. This value is a reference value and is not necessarily accurate to public final boolean isLoaded () // load the file content to the memory as much as possible public final MappedByteBuffer load () // force synchronize the modifications to the memory to the hard disk public final MappedByteBuffer force ()
Message Queue
After learning about the usage of the memory ing file, let's look at how to use it to design and implement a simple message queue, which we call BasicQueue.
Function
BasicQueue is a first-in-first-out cyclic queue with a fixed length. The interface is mainly used for queuing and queuing. The difference between BasicQueue and the container class described earlier is:
- Messages are stored persistently in files, so messages will not be lost when the program is restarted.
- Different programs can collaborate. A typical scenario is that there are two different programs, one is the producer and the other is the consumer. The producer only puts messages in the queue, the consumer only obtains messages from the queue, and the two programs collaborate through the queue. This collaboration method is more flexible and less dependent on each other, and is a common collaboration method.
The BasicQueue construction method is:
public BasicQueue(String path, String queueName) throws IOException
Path indicates the directory where the queue is located and must already exist. queueName indicates the queue name. BasicQueue will store the queue information in two files starting with queueName. One suffix is. data to save the actual message. The other suffix is. meta: stores metadata information. If the two files exist, an existing queue is used. Otherwise, a new queue is created.
BasicQueue provides two methods:
// Enter the public void enqueue (byte [] data) throws IOException // The public byte [] dequeue () throws IOException
Similar to the BasicDB introduced in the previous section, the message format is also a byte array. The queue length of BasicQueue is limited. If it is full, an exception will be thrown when you call enqueue, and the maximum message length is limited. It cannot exceed 1020. If it exceeds, an exception will also be thrown. If the queue is empty, dequeue returns null.
Usage example
The typical use of BasicQueue is the collaboration between producers and consumers. Let's look at the simple sample code. The producer program places messages to the queue. Every time a message is put, the producer takes a random rest for a while. The Code is as follows:
public class Producer { public static void main(String[] args) throws InterruptedException { try { BasicQueue queue = new BasicQueue("./", "task"); int i = 0; Random rnd = new Random(); while (true) { String msg = new String("task " + (i++)); queue.enqueue(msg.getBytes("UTF-8")); System.out.println("produce: " + msg); Thread.sleep(rnd.nextInt(1000)); } } catch (IOException e) { e.printStackTrace(); } }}
The consumer program retrieves messages from the queue. If the queue is empty, it also sleeps for a moment at random. The code is:
public class Consumer { public static void main(String[] args) throws InterruptedException { try { BasicQueue queue = new BasicQueue("./", "task"); Random rnd = new Random(); while (true) { byte[] bytes = queue.dequeue(); if (bytes == null) { Thread.sleep(rnd.nextInt(1000)); continue; } System.out.println("consume: " + new String(bytes, "UTF-8")); } } catch (IOException e) { e.printStackTrace(); } }}
Assuming that the current directories of the two programs are the same, they will use the same queue "task ". Run these two programs at the same time and you will see their output alternate.
Design
We use the following simple method to design BasicQueue:
- Two files are used to save the message queue. One is the data file, the suffix is. data, and the other is the metadata file. meta.
- In the. data file, each piece of information is stored with a fixed length. The length is 1024. The first four bytes are the actual length, followed by the actual content. The maximum length of each message cannot exceed 1020.
- In. the meta file stores the queue header and tail, pointing. the position in the data file is initially 0. When the data file is added to the queue, the system adds a header to the queue and starts from 0 to the end to simulate the cyclic queue.
- To distinguish the full and empty statuses of a queue, the queue is always empty when the queue header and tail are the same, when the next position at the end of the queue is the queue header, the queue is full.
Shows the basic design:
For simplicity, we do not consider consistency issues caused by concurrent access.
Message Queue implementation
The following describes the implementation code of BasicQueue.
Constant Definition
The following constants are defined in BasicQueue. Their names and meanings are as follows:
// Maximum number of messages in a queue. The actual number is also reduced by 1 private static final int MAX_MSG_NUM = 1020*1024; // Maximum length of the message body: private static final int MAX_MSG_BODY_SIZE = 1020; // The space occupied by each message is private static final int MSG_SIZE = MAX_MSG_BODY_SIZE + 4; // the size of the private static final int DATA_FILE_SIZE = MAX_MSG_NUM * MSG_SIZE; // queue metadata file size (head + tail) private static final int META_SIZE = 8;
Internal components
The BasicQueue is mainly composed of two MappedByteBuffer members, which respectively indicate data and metadata:
private MappedByteBuffer dataBuf;private MappedByteBuffer metaBuf;
Constructor
The BasicQueue constructor code is:
public BasicQueue(String path, String queueName) throws IOException { if (path.endsWith(File.separator)) { path += File.separator; } RandomAccessFile dataFile = null; RandomAccessFile metaFile = null; try { dataFile = new RandomAccessFile(path + queueName + ".data", "rw"); metaFile = new RandomAccessFile(path + queueName + ".meta", "rw"); dataBuf = dataFile.getChannel().map(MapMode.READ_WRITE, 0, DATA_FILE_SIZE); metaBuf = metaFile.getChannel().map(MapMode.READ_WRITE, 0, META_SIZE); } finally { if (dataFile != null) { dataFile.close(); } if (metaFile != null) { metaFile.close(); } }}
Auxiliary Methods
To facilitate access to and modify the header and tail pointer of a queue, we have the following methods:
private int head() { return metaBuf.getInt(0);}private void head(int newHead) { metaBuf.putInt(0, newHead);}private int tail() { return metaBuf.getInt(4);}private void tail(int newTail) { metaBuf.putInt(4, newTail);}
To facilitate the determination of whether the queue is empty or full, we have the following methods:
private boolean isEmpty(){ return head() == tail();}private boolean isFull(){ return ((tail() + MSG_SIZE) % DATA_FILE_SIZE) == head();}
Join
Code:
public void enqueue(byte[] data) throws IOException { if (data.length > MAX_MSG_BODY_SIZE) { throw new IllegalArgumentException("msg size is " + data.length + ", while maximum allowed length is " + MAX_MSG_BODY_SIZE); } if (isFull()) { throw new IllegalStateException("queue is full"); } int tail = tail(); dataBuf.position(tail); dataBuf.putInt(data.length); dataBuf.put(data); if (tail + MSG_SIZE >= DATA_FILE_SIZE) { tail(0); } else { tail(tail + MSG_SIZE); }}
The basic logic is:
Team-out
Code:
public byte[] dequeue() throws IOException { if (isEmpty()) { return null; } int head = head(); dataBuf.position(head); int length = dataBuf.getInt(); byte[] data = new byte[length]; dataBuf.get(data); if (head + MSG_SIZE >= DATA_FILE_SIZE) { head(0); } else { head(head + MSG_SIZE); } return data;}
The basic logic is:
Summary
This section describes the basic concepts of memory ing files and their usage in Java. In common file reads and writes, we use less, but in some system programs, it is a commonly used tool that can efficiently read and write large files and achieve sharing and communication between different programs.
Using the memory ing file, we designed and implemented a simple message queue, which can ensure message persistence and achieve cross-program producer/consumer communication, we demonstrated the functions, usage, design, and implementation code of this message queue.
In the previous sections, we have mentioned the serialization concept multiple times. What is it?
----------------
For more information, see the latest article. Please pay attention to the Public Account "lauma says programming" (scan the QR code below), from entry to advanced, ma and you explore the essence of Java programming and computer technology. Retain All copyrights with original intent.