Java NIO interprocess Communication

Source: Internet
Author: User
Tags readable

Transferred from: http://blog.csdn.net/lingzhm/article/details/45026119

The traditional way of interprocess communication is broadly as follows:

(1) Piping (pipe)
(2) Named pipes (FIFO)
(3) Signal Volume (Semphore)
(4) Message Queuing (MessageQueue)
(5) Shared memory (sharedmemory)
(6) Socket

How Java supports inter-process communication. We understand the Java process as a JVM process. It is clear that most of these traditional technologies cannot be exploited by our applications (these interprocess communication is implemented by system calls). But there are many ways in which Java can communicate between processes.
In addition to the socket mentioned above, of course the preferred IPC can use RMI, or CORBA can also. In addition, Java NiO's mappedbytebuffer can also be used to implement interprocess communication (shared memory) through a memory-mapped file.

The approach that Java interprocess communication can take:

Socket/rmi/webservice/webserver, all of which enable direct data exchange
Database/file, these allow for indirect data exchange

See if your business requires real-time, and if not, it's easier to Exchange databases

Inter-thread communication:

It can be implemented directly by passing in shared variables.


The memory-mapped file (mappedbytebuffer) of Java NIO makes me immediately associate the memory-mapped file of the Windows system. The memory-mapped file of a Windows system can be used to share data among multiple processes, that is, shared memory between processes, by mapping the same piece of memory to the address space of a different process to achieve shared memory.

Java NIO's memory-mapped files, like the Windows system, can map the contents of physical files to memory, so can mappedbytebuffer be used to share data between different Java processes (JVMs)? The answer is yes, so there is one more way to implement Java interprocess communication in the usual Socket way.

In Windows, a memory-mapped file can be a named area of memory that exists from a physical file, using the same memory-mapped name to share the same piece of memory in different processes. Then, Java's mappedbytebuffer is always associated with a physical file, because whether you're from FileInputStream, FileOutputStream or Randomaccessfile FileChannel, Map () The resulting memory-mapped file mappedbytebuffer If you do not specify a physical file when constructing FileInputStream, FileOutputStream, Randomaccessfile objects FileNotFoundException exception.

So the way Java NIO implements shared memory is to have the memory-mapped files of different processes associated with the same physical file, because Mappedbytebuffer can synchronize the contents of the memory with the files instantly. Strictly speaking, called memory sharing is not accurate, in fact, two Java process through the intermediate files to exchange data, with the intermediate file to make two processes of two memory area of the contents of the timely synchronization.

To understand the implementation principle of Java NIO's "Shared memory" using graphs:

Once you know the implementation principle, the following code demonstrates two processes using memory-mapped files for data communication. Code Writesharememory.java to the map file, write A, B, C ... Z,readsharememory.java read it one by one and print it to the screen. The code reads and writes the first byte of the interchange file swap.mm, which is 0-readable, 1-in-writing, and 2-readable. The channel obtained by Randomaccessfile can be read or written flexibly without destroying the contents of the original file, and the channel obtained by FileInputStream or fileoutputstream is difficult to achieve this effect, so the use of Randomaccessfile to get FileChannel.

Writesharememory.java

0102030405060708091011121314151617181920212223242526272829303132333435363738394041424344454647 packagecom.unmi;import java.io.RandomAccessFile;importjava.nio.MappedByteBuffer;importjava.nio.channels.FileChannel;importjava.nio.channels.FileChannel.MapMode;/** * 往 "共享内存" 写入数据 * @author Unmi */public classWriteShareMemory {    /**     * @param args     * @throws Exception     */    publicstaticvoid main(String[] args) throwsException {        RandomAccessFile raf = newRandomAccessFile("c:/swap.mm""rw");        FileChannel fc = raf.getChannel();        MappedByteBuffer mbb = fc.map(MapMode.READ_WRITE, 01024);        //清除文件内容        for(inti=0;i<1024;i++){            mbb.put(i,(byte)0);        }        //从文件的第二个字节开始,依次写入 A-Z 字母,第一个字节指明了当前操作的位置        for(int i=65;i<91;i++){            intindex = i-63;            intflag = mbb.get(0); //可读标置第一个字节为 0            if(flag != 0){ //不是可写标示 0,则重复循环,等待                i --;                continue;            }            mbb.put(0,(byte)1); //正在写数据,标志第一个字节为 1            mbb.put(1,(byte)(index)); //写数据的位置             System.out.println("程序 WriteShareMemory:"+System.currentTimeMillis() +                    ":位置:"+ index +" 写入数据:"+ (char)i);            mbb.put(index,(byte)i);//index 位置写入数据            mbb.put(0,(byte)2); //置可读数据标志第一个字节为 2            Thread.sleep(513);        }    }}
This article original link http://unmi.cc/java-nio-memory-mapping-communicate/, from Yehuang Unmi Blog

Readsharememory.java

0102030405060708091011121314151617181920212223242526272829303132333435363738394041424344 packagecom.unmi;importjava.io.RandomAccessFile;importjava.nio.MappedByteBuffer;importjava.nio.channels.FileChannel;importjava.nio.channels.FileChannel.MapMode;/** * 从 "共享内存" 读出数据 * @author Unmi */publicclassReadShareMemory {    /**     * @param args     * @throws Exception     */    publicstaticvoid main(String[] args) throwsException {        RandomAccessFile raf = newRandomAccessFile("c:/swap.mm""rw");        FileChannel fc = raf.getChannel();        MappedByteBuffer mbb = fc.map(MapMode.READ_WRITE, 01024);        intlastIndex = 0;        for(inti=1;i<27;i++){            intflag = mbb.get(0); //取读写数据的标志            intindex = mbb.get(1); //读取数据的位置,2 为可读             if(flag != 2|| index == lastIndex){ //假如不可读,或未写入新数据时重复循环                i--;                continue;            }            lastIndex = index;            System.out.println("程序 ReadShareMemory:"+ System.currentTimeMillis() +                    ":位置:"+ index +" 读出数据:" + (char)mbb.get(index));            mbb.put(0,(byte)0); //置第一个字节为可读标志为 0            if(index == 27){ //读完数据后退出                break;            }        }    }}

Run Writesharememory in Eclipse and run readsharememory under the command line, and you'll see Writesharememory write a character, Readsharememory read one.

Read-write flags are used in the code, and the index position is written, so after Writesharememory writes a character, the second character is written only after waiting for Readsharememory to read the characters that have just been written. In the actual application can be added better notification methods, such as file locks.

You can also check the contents of the c:\swap.mm file at execution time to verify this process, because Mappedbytebuffer is a directbytebuffer at runtime, so it can synchronize content instantly with the file without having to write through FileChannel (buffer) writes the data manually to the file, or read (buffer) reads the data manually into memory.

Reference: 1. Implementations and applications in Java that exist within a share

This article links http://unmi.cc/java-nio-memory-mapping-communicate/, from Yehuang Unmi Blog

Java NIO interprocess Communication

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.