Java NIO Applications-interprocess communication using memory-mapped files

Source: Internet
Author: User

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


01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21st

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

Package Com.unmi;

Import Java.io.RandomAccessFile;

Import Java.nio.MappedByteBuffer;

Import Java.nio.channels.FileChannel;

Import Java.nio.channels.FileChannel.MapMode;

/**

* Write data to "shared memory"

* @author Unmi

*/

public class Writesharememory {

/**

* @param args

* @throws Exception

*/

public static void Main (string[] args) throws Exception {

Randomaccessfile RAF = new Randomaccessfile ("c:/swap.mm", "RW");

FileChannel FC = Raf.getchannel ();

Mappedbytebuffer MBB = Fc.map (mapmode.read_write, 0, 1024);

Purge File contents

for (int i=0;i<1024;i++) {

Mbb.put (i, (byte) 0);

}

Start with the second byte of the file, write a A-Z letter, and the first byte indicates the position of the current operation

for (int i=65;i<91;i++) {

int index = i-63;

int flag = mbb.get (0); Readable superscript The first byte is 0

if (flag! = 0) {//not writable 0, repeat loop, wait

I--;

Continue

}

Mbb.put (0, (byte) 1); Writing data, flag first byte is 1

Mbb.put (1, (byte) (index)); Where to write data

SYSTEM.OUT.PRINTLN ("program writesharememory:" +system.currenttimemillis () +

": Location:" + index + "Write data:" + (char) i);

Mbb.put (index, (byte) i);//index position Write data

Mbb.put (0, (byte) 2); Set readable data flag the first byte is 2

Thread.Sleep (513);

}

}

}

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

Readsharememory.java


01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21st

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

Package Com.unmi;

Import Java.io.RandomAccessFile;

Import Java.nio.MappedByteBuffer;

Import Java.nio.channels.FileChannel;

Import Java.nio.channels.FileChannel.MapMode;

/**

* Read data from "Shared memory"

* @author Unmi

*/

public class Readsharememory {

/**

* @param args

* @throws Exception

*/

public static void Main (string[] args) throws Exception {

Randomaccessfile RAF = new Randomaccessfile ("c:/swap.mm", "RW");

FileChannel FC = Raf.getchannel ();

Mappedbytebuffer MBB = Fc.map (mapmode.read_write, 0, 1024);

int lastIndex = 0;

for (int i=1;i<27;i++) {

int flag = mbb.get (0); Flags for reading and writing data

int index = mbb.get (1); The location where the data is read, 2 is readable

if (flag! = 2 | | index = = lastIndex) {//if unreadable, or if no new data is written, repeat loops

i--;

Continue

}

LastIndex = index;

SYSTEM.OUT.PRINTLN ("program readsharememory:" + system.currenttimemillis () +

": Location:" + index + "readout data:" + (char) mbb.get (index));

Mbb.put (0, (byte) 0); Set the first byte to be a readable flag of 0

if (index = = 27) {//Log out after reading data

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.


Java NIO Applications-interprocess communication using memory-mapped files

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.