Java Shared memory

Source: Internet
Author: User
Tags flock

1 shared memory corresponds to the significance of application development
The IPC (interprocess communication) mechanism is familiar to programmers familiar with the application development of UNIX systems, and the IPC basically includes shared memory, semaphore operation, Message Queuing, signal processing and other parts, which is an essential tool in the development of applications. The key to the IPC mechanism of shared memory is the unique advantages for data sharing, System quick query, dynamic configuration, and reducing resource consumption.

For UNIX systems, shared memory is divided into common shared memory and image file shared memory, which corresponds to Windows, which is actually only one of the image file share memory. So you can only create image file shared memory in Java applications.

In the Java language, there is basically no mention of the concept of shared memory, but in some applications, shared memory is really very useful, such as in the Java language Distributed Application system, there are a large number of distributed shared objects, many times need to query the state of these objects, To see if the system is functioning properly or to understand some of the current statistics and status of these objects. If you use network communication, it will obviously increase the additional burden of the application, but also add some unnecessary application programming. In the case of shared memory, the state data and statistics of the object can be viewed directly through shared memory, which reduces unnecessary hassles.

The use of shared memory is characterized by the following:

Access can be opened by multiple processes;
The process of read and write operations cannot write to other processes while performing read and write operations;
Multiple processes can perform write operations on a shared memory alternately;
After a process has performed a write operation on the memory, it does not affect the access of other processes to that memory. At the same time, other processes have visibility of the updated memory.
If an exception exits while the process is performing a write operation, the write operation on other processes is forbidden to be automatically dismissed.
Relative to shared files, the convenience and efficiency of data access are


In addition, the use of shared memory has the following conditions:

Exclusive write operation, corresponding to an exclusive write operation waiting queue. The exclusive write operation itself does not occur with data consistency issues.
A shared write operation, corresponding to a shared write operation waiting queue. The shared write operation is to be aware of the problem of preventing data consistency.
Exclusive read operation, corresponding to a shared read operation waiting queue;
Shared read operation, corresponding to a shared read operation waiting queue.


In general, we are only concerned with the 12th case.

2 implementations in Java exist within a share
The class Mappedbytebuffer provided in jdk1.4 provides a good way for us to implement shared memory. The buffer is actually a memory image of a disk file. The changes will be kept in sync, i.e. changes in memory data are immediately reflected in the disk file, which effectively guarantees the implementation of shared memory.

The shared memory and disk files are linked to the file Channel class: FileChannel. This class is added to the JDK in order to unify the external device (file, network interface, etc.) access method, and enhance the multi-threaded access to the same file security. For example, read and write operations are unified into read and write. This is used only to create shared memory, which establishes a channel between shared memory and disk files.

Open a file to create a file channel you can use the method Getchannel in the Randomaccessfile class. The method will return a file channel directly. The file channel because the corresponding file is set to random Access file, on the one hand can read and write two operations, on the other hand it will not destroy the image file content (if you open an image file directly with FileOutputStream will be the size of the file to 0, of course, the data will be lost). Here, it is not desirable to use fileoutputstream and fileinputstream to achieve shared memory requirements, because these two classes are much more difficult to achieve while simultaneously achieving free read and write operations.

The following code implements the above function, which acts like a mmap function in a UNIX system.

     get a read-only random Access file object    randomaccessfile   rafile   =   new   randomaccessfile (filename, "R");   get the appropriate file channel    FileChannel   fc   =   Rafile.getchannel ();   gets the actual size of the file so that it is imaged to the shared memory    int   size   =   (int) fc.size ();   get the shared memory buffer, the shared memory is    read   -only mappedbytebuffer mapbuf   =   fc.map (filechannel.map_ro,0,size);   get a read-write random Access file object    rafile   =   new   randomaccessfile (filename, "RW");   obtain the corresponding file channel    fc   =   Rafile.getchannel ();   gets the actual size of the file so that it is imaged to shared memory    size   =   (int) fc.size ();   gets the shared memory buffer, which can read and write    mapbuf   =   fc.map (filechannel.map_rw,0,size);   Get header message: Access rights    Mode   =   mapbuf.getint ();   



If multiple apps image shared memory of the same file name, it means that the same memory data is shared by the multiple apps. These apps can have equal access to the file, and an app refresh of the data is updated to multiple apps.

To prevent multiple applications from writing to shared memory at the same time, a write flag can be added to the header information of the shared memory. The header basic information for this shared memory is at least:

   the length of int length;//   shared memory.    int   mode;   the current access mode of the shared memory.      





The header information of the shared memory is the private information of the class, and when multiple applications can perform write operations on the same shared memory, the following methods need to be called when the write and end write operations are started:

Public   Boolean   startwrite ()    {    if (mode   = =   0)   {   //flag =   0 indicates    writable Mode   =   1;   a flag of 1 means that no other application can write the shared memory    Mapbuf.flip ();      Mapbuf.putint (mode);   Write header information such as shared memory    return   true;    else   {    return   false;   indicates that there is already an application writing the shared memory, the application cannot write the shared memory    }    } public   boolean   stopwrite ()    {    mode   =   0;   Release Write permission    mapbuf.flip ();      Mapbuf.putint (mode);   Write Shared memory header information    return   true;       




The class file provided here Mmap.java encapsulates the basic interface for shared memory, which the reader can use to expand into a fully functional class of its own.


If the application that performs the write operation aborts abnormally, the shared memory of the image file will no longer be able to perform a write operation. In order to disable flag auto-elimination after an exception abort is applied, the running app must be informed of the exiting application. In multi-threaded applications, this can be achieved with synchronous methods, but in multiple processes, synchronization is ineffective. Methods can be used in a variety of techniques, here is just a description of the possible implementation: the use of file lock method. Write shared memory application in the acquisition of a shared memory write permission, in addition to determine the header information Write permission flag, but also to determine whether a temporary lock file can be obtained, if you can get, even if the header information Write permission flag is 1 (above), you can also start write permissions, In fact, this has already indicated that the application that the Write permission obtains has exited unexpectedly, this code is as follows:

     open a temporary file, note the same shared memory, the file name is the same, you can add the suffix ". Lock" After the file name is shared.    randomaccessfile   fis   =   new   randomaccessfile ("Shm.lock", "RW");   get file Channel    filechannel   lockfc   =   fis.getchannel ();   obtains the exclusive lock of the file, the method does not produce the blockage, immediately returns    Filelock   flock   =   lockfc.trylock ();   if it is empty, it indicates that there is already an application that occupies the lock    if (flock   = =   null)   {    ...//   cannot perform a write operation    }    Else   {    ...//   can perform write    }      




The lock is automatically released after the application exits unexpectedly, which is exactly what the method requires.


3 Apps in Java that exist within a share
There are two applications in a shared Java application, often as follows:

Permanent object configuration.
In a Java server application, the user may configure some parameters during the run, which need to be permanently valid, and these configuration parameters can still work on the app after the server app restarts. This allows you to use the shared memory in this article. The shared memory holds the server's running parameters and some object run characteristics. You can read in to enable previously configured parameters when the app starts.

Querying shared data.
An application (example Sys.java) is a service process of a system whose operating state is recorded in shared memory, where the running state may be constantly changing. To keep abreast of the operating state of the system, launch another application (example Mon.java), which queries the shared memory and reports the system's operational status.

It can be seen that in the Java application is still useful in the sharing, as long as the organization of the shared memory of the data structure, the shared memory will play a very good role in application development.

You can actually test the following program processing:

      Public Quickfind () {.....                FileChannel fch = new Randomaccessfile (path, "R"). Getchannel ();                Bytebuffer robuf = Fch.map (FileChannel.MapMode.READ_ONLY, 0, (int) fch.size ());                DataInputStream is = new DataInputStream (Newinputstream (ROBUF));                String AA = "";              while (true) {AA = Is.readline ();             .....                .....        }   public static InputStream Newinputstream (final Bytebuffer buf) {return new InputStream () {public synchronized int read () throws IOException {I                                F (!buf.hasremaining ()) {return-1;                        } return Buf.get ();   } public synchronized intRead (byte[] bytes, int off, int len) throws IOException {//Read only                                What's Left len = Math.min (len, buf.remaining ());                                Buf.get (bytes, off, Len);                        return Len;        }                };    }


Speed should be able to improve many

Java Shared memory

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.