code_money_guji's Blog

Happy coding

NIO Memory-Mapped Files

code_money_guji posted @ 2011年2月27日 00:09 in javaNIO & Mina , 1627 阅读

参考资料:

     http://www.linuxtopia.org/online_books/programming_books/thinking_in_java/TIJ314_029.htm Thinking in java

    //一个比较好的测试Sample

     Reille_java_NIO

http://www.javadocexamples.com/java/nio/channels/java.nio.channels.FileChannel.MapMode.html  map参数中的 READ_ONLY|READ_WRITE|PRIVATE示例

//JDK 文档的使用示例,有很多的例子.十分有用.

Memory-Mapped Files:

Memory-Mapped Files 允许将文件直接映射到内存中读取. 在map()方法中, 其中的一个参数是:MapMode,有如下说明:

MapMode.READ_ONLY: 但尝试从这种模式写入内容的时候会触发:ReadOnlyBufferException

MapMode.READ_WRITE : 映射读|写,能够把同一个文件的更改结果传播.

MapMode.PRIVATE :  使用Copy-on-write的方式,私有修改.

NOTE:

MapMode.READ_ONLY: 使用这种模式的时候,在同一个文件中的不同buffer之间的更改能够更改文件, 所以其他buffer能够"觉察"到改变.

MapMode.PRIVATE:这种模式下, 由于使用了Copy的方式, 改变的内容不会传播到文件中, 每个buffer中的内容是独立的, 假设有buffer1 和buffer2.那么在buffer1中的改变时不会在buffer2中观察到.  根本原因是这种方式下buffer1中的改变不会回显到文件中.

下面是Thinking in java 中的性能测试代码,除了其能进行结果证明外,其用的测试方法也编写代码的一个规范,感谢作者:

    //: c12:MappedIO.java
    // {Clean: temp.tmp}
    import java.io.*;
    import java.nio.*;
    import java.nio.channels.*;

    public class MappedIO {
      private static int numOfInts = 4000000;
      private static int numOfUbuffInts = 200000;
      private abstract static class Tester {
        private String name;
        public Tester(String name) { this.name = name; }
        public long runTest() {
          System.out.print(name + ": ");
          try {
            long startTime = System.currentTimeMillis();
            test();
            long endTime = System.currentTimeMillis();
            return (endTime - startTime);
          } catch (IOException e) {
            throw new RuntimeException(e);
          }
        }
        public abstract void test() throws IOException;
      }
 //上述的代使用的模板方法很不仅仅是在测试中,在框架使用中处处可见.
      private static Tester[] tests = { 
        new Tester("Stream Write") {
          public void test() throws IOException {
            DataOutputStream dos = new DataOutputStream(
              new BufferedOutputStream(
                new FileOutputStream(new File("temp.tmp"))));
            for(int i = 0; i < numOfInts; i++)
              dos.writeInt(i);
            dos.close();
          }
        }, 
        new Tester("Mapped Write") {
          public void test() throws IOException {
            FileChannel fc = 
              new RandomAccessFile("temp.tmp", "rw")
              .getChannel();
            IntBuffer ib = fc.map(
              FileChannel.MapMode.READ_WRITE, 0, fc.size())
              .asIntBuffer();
            for(int i = 0; i < numOfInts; i++)
              ib.put(i);
            fc.close();
          }
        }, 
        new Tester("Stream Read") {
          public void test() throws IOException {
            DataInputStream dis = new DataInputStream(
              new BufferedInputStream(
                new FileInputStream("temp.tmp")));
            for(int i = 0; i < numOfInts; i++)
              dis.readInt();
            dis.close();
          }
        }, 
        new Tester("Mapped Read") {
          public void test() throws IOException {
            FileChannel fc = new FileInputStream(
              new File("temp.tmp")).getChannel();
            IntBuffer ib = fc.map(
              FileChannel.MapMode.READ_ONLY, 0, fc.size())
              .asIntBuffer();
            while(ib.hasRemaining())
              ib.get();
            fc.close();
          }
        }, 
        new Tester("Stream Read/Write") {
          public void test() throws IOException {
            RandomAccessFile raf = new RandomAccessFile(
              new File("temp.tmp"), "rw");
            raf.writeInt(1);
            for(int i = 0; i < numOfUbuffInts; i++) {
              raf.seek(raf.length() - 4);
              raf.writeInt(raf.readInt());
            }
            raf.close();
          }
        }, 
        new Tester("Mapped Read/Write") {
          public void test() throws IOException {
            FileChannel fc = new RandomAccessFile(
              new File("temp.tmp"), "rw").getChannel();
            IntBuffer ib = fc.map(
              FileChannel.MapMode.READ_WRITE, 0, fc.size())
              .asIntBuffer();
            ib.put(0);
            for(int i = 1; i < numOfUbuffInts; i++)
              ib.put(ib.get(i - 1));
            fc.close();
          }
        }
      };
      public static void main(String[] args) {
        for(int i = 0; i < tests.length; i++)
          System.out.println(tests[i].runTest());
      }
    } ///:~

运行结果[趋势相同,不同配置时间花费会不一样]:
Stream Write: 1719
Mapped Write: 359
Stream Read: 750
Mapped Read: 125
Stream Read/Write: 5188
Mapped Read/Write: 16

 如果是文件太大,不妨考取在使用map()方法的时候,限定length的范围.

 注意点,在 REILLE_JAVA_NIO 一书中,有如下的话:

Accessing a file through the memory-mapping mechanism can be far more efficient than reading or writing data by conventional means, even when using channels. No explicit system calls need to be made, which can be time-consuming. More importantly, the virtual memory system of the operating system automatically caches memory pages. These pages will be cached using system memory and will not consume space from the JVM's memory heap.

从上面的话看出,使用这种方式是映射到OS的虚拟内存中,并不是jvm heap中.

 

结束语:

至于并行操作MappedByteBuffer性能如何,笔者未曾测试,有机会发现应用场景的话会及时更新文章. 也希望大家能够多提出这方面的需求与应用. thanks.

to be continue..

 

 

Avatar_small
seo service UK 说:
2023年12月06日 22:39

I like your post and also like your website because your website is very fast and everything in this website is good. Keep writing such informative posts. I have bookmark your website. Thanks for sharin

Avatar_small
먹튀폴리스주소 说:
2023年12月19日 14:26

Outstanding article!  I want people to know just how good this information is in your article. Your views are much like my own concerning this subject. I will visit daily your blog because I know. It may be very beneficial for me.

Avatar_small
룰루랄라 도메인 说:
2023年12月19日 15:10

Wonderful blog! I found it while surfing around on Yahoo News. Do you have any suggestions on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Appreciate it. I know this is one of the most meaningful information for me. And I'm animated reading your article. But should remark on some general things, the website style is perfect; the articles are great. Thanks for the ton of tangible and attainable help. Thank you for another great article. Where else could anyone get that kind of information in such a perfect way of writing.

Avatar_small
스타벳 이벤트 혜택 说:
2023年12月19日 15:25

Thank you for sharing a bunch of this quality contents, I have bookmarked your blog. Please also explore advice from my site. I will be back for more quality contents. 

Avatar_small
메이저놀이터 说:
2023年12月19日 15:44

An impressive share, I merely with all this onto a colleague who had previously been conducting a little analysis within this. And that he the truth is bought me breakfast simply because I uncovered it for him.. here------------- I gotta bookmark this website it seems very useful very helpful. I enjoy reading it. I fundamental to learn more on this subject.. Thanks for the sake theme this marvellous post.. Anyway, I am gonna subscribe to your silage and I wish you post again soon. I am curious to find out what blog system you are utilizing? I’m having some minor security problems with my latest website and I would like to find something more secure.

Avatar_small
토토사이트 说:
2023年12月19日 16:03

I am impressed by the information that you have on this blog. It shows how well you understand this subject. wow... what a great blog, this writter who wrote this article it's realy a great blogger, this article so inspiring me to be a better person . Through this post, I know that your good knowledge in playing with all the pieces was very helpful. I notify that this is the first place where I find issues I've been searching for. You have a clever yet attractive way of writing. Cool stuff you have and you keep overhaul every one of us 

Avatar_small
먹튀검증커뮤니티 说:
2023年12月19日 16:29

I think I have never seen such blogs ever before that has complete things with all details which I want. So kindly update this ever for us

Avatar_small
안전놀이터검증 说:
2023年12月19日 16:45

Pleasant article.Think so new type of elements have incorporated into your article. Sitting tight for your next article . I am happy to find this post Very useful for me, as it contains lot of information. I Always prefer to read The Quality and glad I found this thing in you post. Thanks . This surely helps me in my work. Lol, thanks for your comment! wink Glad you found it helpful . These are just a couple of things to think about when looking for sports betting books and systems. Good Day! The way you have written your post is so nice. Very professional . Keep writing this amazing post.

Avatar_small
메이저사이트 说:
2023年12月19日 16:47

severely of which saintly all the same, I adore people go in on top of that satisfying shots might be feature personss damaging get pleasure from increasingly being defrent mind overall poeple, 

Avatar_small
먹튀스텟 도메인 说:
2023年12月19日 17:04

I admire what you have done here. I like the part where you say you are doing this to give back but I would assume by all the comments that this is working for you as well. Thank you for some other informative blog. Where else could I get that type of information written in such an ideal means? I have a mission that I’m just now working on, and I have been at the look out for such information. Your content is nothing short of brilliant in many ways. I think this is engaging and eye-opening material. Thank you so much for caring about your content and your readers.

Avatar_small
토토사이트 说:
2023年12月19日 17:39

Did you create this website yourself? Please reply back as I'm planning to create my own personal blog and would like to learn where you got this from or exactly what the theme is called.

Avatar_small
먹튀사이트 说:
2023年12月19日 17:44

hey there i stumbled upon your website searching around the web. I wanted to say I like the look of things around here. Keep it up will bookmark for sure. Cool you write, the information is very good and interesting, I'll give you a link to my site. you have got a great blog here! do you want to make some invite posts in my blog. Thanks for an interesting blog. What else may I get that sort of info written in such a perfect approach? I have an undertaking that I am just now operating on, and I have been on the lookout for such info.

Avatar_small
파워사다리사이트 说:
2023年12月19日 17:46

hey there i stumbled upon your website searching around the web. I wanted to say I like the look of things around here. Keep it up will bookmark for sure. Cool you write, the information is very good and interesting, I'll give you a link to my site. you have got a great blog here! do you want to make some invite posts in my blog. Thanks for an interesting blog. What else may I get that sort of info written in such a perfect approach? I have an undertaking that I am just now operating on, and I have been on the lookout for such info.

Avatar_small
먹튀중개소역할 说:
2023年12月19日 18:00

Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too.I'm glad I found this web site, I couldn't find any knowledge on this matter prior to.Also operate a site and if you are ever interested in doing some visitor writing for me if possible feel free to let me know, im always look for people to check out my web site. 

Avatar_small
메이저놀이터 说:
2023年12月19日 18:05

You really make it appear really easy together with your presentation however I find this matter to be actually something which I feel I’d by no means understand. 

Avatar_small
안전놀이터 说:
2023年12月19日 18:11

Nice post. I learn some thing tougher on different blogs everyday. Most commonly it is stimulating to read content off their writers and practice something at their store. I’d opt to use some with all the content in my weblog whether or not you do not mind. Natually I’ll provide a link with your internet weblog. Thank you for sharing 

Avatar_small
토디즈 说:
2023年12月19日 18:20

Nice post. I learn some thing tougher on different blogs everyday. Most commonly it is stimulating to read content off their writers and practice something at their store. I’d opt to use some with all the content in my weblog whether or not you do not mind. Natually I’ll provide a link with your internet weblog. Thank you for sharing 

Avatar_small
크랩스게임방법 说:
2023年12月19日 18:49

I found that site very usefull and this survey is very cirious, I ' ve never seen a blog that demand a survey for this actions, very curious...

Avatar_small
메이저토토사이트 说:
2023年12月19日 18:50

Cool you write, the information is very good and interesting, I'll give you a link to my site. I am very enjoyed for this blog. Its an informative topic. It help me very much to solve some problems. Its opportunity are so fantastic and working style so sp

Avatar_small
먹튀신고 说:
2023年12月19日 18:59

Pleasant article.Think so new type of elements have incorporated into your article. Sitting tight for your next article . I am happy to find this post Very useful for me, as it contains lot of information. I Always prefer to read The Quality and glad I found this thing in you post. Thanks . This surely helps me in my work. Lol, thanks for your comment! wink Glad you found it helpful . These are just a couple of things to think about when looking for sports betting books and systems. Good Day! The way you have written your post is so nice. Very professional . Keep writing this amazing post.

Avatar_small
우리카지노 说:
2023年12月19日 19:00

`These is apparently just like definitely great. Most of these modest items are designed through the use of variety of base consciousness. I love these significantly 

Avatar_small
해외사이트 说:
2023年12月19日 19:03

Thank you for sharing a bunch of this quality contents, I have bookmarked your blog. Please also explore advice from my site. I will be back for more quality contents. 

Avatar_small
해외토토사이트 说:
2023年12月19日 19:18

An impressive share, I merely with all this onto a colleague who had previously been conducting a little analysis within this. And that he the truth is bought me breakfast simply because I uncovered it for him.. here------------- I gotta bookmark this website it seems very useful very helpful. I enjoy reading it. I fundamental to learn more on this subject.. Thanks for the sake theme this marvellous post.. Anyway, I am gonna subscribe to your silage and I wish you post again soon. I am curious to find out what blog system you are utilizing? I’m having some minor security problems with my latest website and I would like to find something more secure.

Avatar_small
토토사이트추천 说:
2023年12月19日 19:19

These is apparently just like definitely great. Most of these modest items are designed through the use of variety of base consciousness. I love these significantly

Avatar_small
안전놀이터 说:
2023年12月19日 19:29

I am impressed by the information that you have on this blog. It shows how well you understand this subject. wow... what a great blog, this writter who wrote this article it's realy a great blogger, this article so inspiring me to be a better person . Through this post, I know that your good knowledge in playing with all the pieces was very helpful. I notify that this is the first place where I find issues I've been searching for. You have a clever yet attractive way of writing. Cool stuff you have and you keep overhaul every one of us 

Avatar_small
메이저공원1 说:
2023年12月19日 19:33

Unicorn Dating sites have made it easier for people to connect with like-minded individuals for casual encounters, but it's vital to take precautions to ensure your safety when using these sites. Here are some precautions to follow when using your trustworthy unicorn dating app.

Avatar_small
토토어택가입 说:
2023年12月19日 19:50

I think I have never seen such blogs ever before that has complete things with all details which I want. So kindly update this ever for us

Avatar_small
가상스포츠분석법 说:
2023年12月19日 20:01

Did you create this website yourself? Please reply back as I'm planning to create my own personal blog and would like to learn where you got this from or exactly what the theme is called.

Avatar_small
꽁머니토토 说:
2023年12月19日 20:02

An impressive share, I merely with all this onto a colleague who had previously been conducting a little analysis within this. And that he the truth is bought me breakfast simply because I uncovered it for him.. here------------- I gotta bookmark this website it seems very useful very helpful. I enjoy reading it. I fundamental to learn more on this subject.. Thanks for the sake theme this marvellous post.. Anyway, I am gonna subscribe to your silage and I wish you post again soon. I am curious to find out what blog system you are utilizing? I’m having some minor security problems with my latest website and I would like to find something more secure.

Avatar_small
메이저토토 说:
2023年12月19日 20:18

Thank you a bunch for sharing this with all of us you actually realize what you are talking about! Bookmarked. Please also seek advice from my site =). We could have a hyperlink change contract between us! This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information.. Wow, What an exceptional pronounce. i found this too much informatics. it's miles what i used to be searching for for. i'd as soon as to area you that absorb keep sharing such kind of data.If realistic, thank you.

Avatar_small
바카라사이트추천 说:
2023年12月19日 20:27

Thank you a bunch for sharing this with all of us you actually realize what you are talking about! Bookmarked. Please also seek advice from my site =). We could have a hyperlink change contract between us! This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information.. Wow, What an exceptional pronounce. i found this too much informatics. it's miles what i used to be searching for for. i'd as soon as to area you that absorb keep sharing such kind of data.If realistic, thank you.

Avatar_small
파라오카지노 说:
2023年12月19日 20:48

This is my first time i visit here and I found so many interesting stuff in your blog especially it's discussion, thank you. This article gives the light in which we can observe the reality. I am happy to find this post very useful for me, as it contains a lot of information. Thanks for all your help and wishing you all the success in your categories. Thanks for sharing the content for any sort of online business consultation is the best place to find in the town. 

Avatar_small
토토사이트검증 说:
2023年12月19日 21:02

wow, great, I was wondering how to cure acne naturally. and found your site by google, learned a lot, now i’m a bit clear. I’ve bookmark your site and also add rss. keep us updated. This post is very simple to read and appreciate without leaving any details out. Great work! thanks for this article, i suggest you if you want tour company this is best company for toursits in dubai. This is an excellent post I seen thanks to share it.

Avatar_small
롤토토사이트순위 说:
2023年12月19日 21:14

Thank you a bunch for sharing this with all of us you actually realize what you are talking about! Bookmarked. Please also seek advice from my site =). We could have a hyperlink change contract between us! This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information.. Wow, What an exceptional pronounce. i found this too much informatics. it's miles what i used to be searching for for. i'd as soon as to area you that absorb keep sharing such kind of data.If realistic, thank you.

Avatar_small
먹튀폴리스검증업체 说:
2023年12月19日 21:21

Thank you a bunch for sharing this with all of us you actually realize what you are talking about! Bookmarked. Please also seek advice from my site =). We could have a hyperlink change contract between us! This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information.. Wow, What an exceptional pronounce. i found this too much informatics. it's miles what i used to be searching for for. i'd as soon as to area you that absorb keep sharing such kind of data.If realistic, thank you.

Avatar_small
입플사이트추천 说:
2023年12月19日 21:35

Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too.I'm glad I found this web site, I couldn't find any knowledge on this matter prior to.Also operate a site and if you are ever interested in doing some visitor writing for me if possible feel free to let me know, im always look for people to check out my web site. 

Avatar_small
먹튀검증업체 순위 说:
2023年12月19日 21:58

These is apparently just like definitely great. Most of these modest items are designed through the use of variety of base consciousness. I love these significantly 

Avatar_small
토토사이트추천 说:
2024年1月21日 14:50

Thanks for a very interesting blog. What else may I get that kind of info written in such a perfect approach? I’ve a undertaking that I am simply now operating on, and I have been at the look out for such info

Avatar_small
토토사이트추천 说:
2024年1月21日 14:54

Admiring the time and effort you put into your blog and detailed information you offer!.

Avatar_small
바카라사이트 说:
2024年1月21日 17:08

Hello. splendid job. I did not imagine this. This is a impressive articles. Thanks!

Avatar_small
카지노 커뮤니티 说:
2024年1月21日 17:31

I wanted to thank you for this excellent read!! I definitely loved every little bit of it. I have you bookmarked your site to check out the new stuff you post

Avatar_small
먹튀검증 说:
2024年1月21日 18:00

You there, this is really good post here. Thanks for taking the time to post such valuable information. Quality content is what always gets the visitors coming.

Avatar_small
바카라 사이트 说:
2024年1月21日 18:50

Interesting topic for a blog. I have been searching the Internet for fun and came upon your website. Fabulous post. Thanks a ton for sharing your knowledge! It is great to see that some people still put in an effort into managing their websites. I'll be sure to check back again real soon.

Avatar_small
꽁머니 说:
2024年1月21日 19:41

It’s super webpage, I was looking for something like this

Avatar_small
먹튀검증 说:
2024年1月21日 20:32

It is somewhat fantastic, and yet check out the advice at this treat.

Avatar_small
카지노사이트추천 说:
2024年1月21日 20:54

The article posted was very informative and useful. You people are doing a great job. Keep going

Avatar_small
industrial outdoor s 说:
2024年1月22日 13:31

A very Wonderful blog. We believe that you have a busy, active lifestyle and also understand you need marijuana products from time to time. We’re ICO sponsored and in collaboration with doctors, deliveries, storefronts and deals worldwide, we offer a delivery service – rated #1 in the cannabis industry – to bring weed strains straight to you, discretely by our men on ground.

Avatar_small
카지노커뮤니티 说:
2024年1月22日 14:16

This is worth it to read for everyone. Thank you for sharing good ideas to all your readers and continue inspiring us

Avatar_small
소액결제현금화 说:
2024年1月22日 14:45

Very interesting blog. A lot of blogs I see these days don't really provide anything that I'm interested in, but I'm most definitely interested in this one.

Avatar_small
고화질스포츠중계 说:
2024年1月22日 15:20

You there, this is really good post here. Thanks for taking the time to post such valuable information. Quality content is what always gets the visitors coming.

Avatar_small
카지노사이트 说:
2024年1月22日 15:59

You got a very fantastic website, Gladiolus

Avatar_small
카지노사이트 说:
2024年1月24日 16:47

I'm constantly searching on the internet for posts that will help me. Too much is clearly to learn about this. I believe you created good quality items in Functions also. Keep working, congrats

Avatar_small
카지노 说:
2024年1月24日 18:23

I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own Blog Engine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it

Avatar_small
토토검증사이트 说:
2024年1月24日 19:58

You had a marvelous handle on the theme, nonetheless you fail to consolidate your perusers. Perhaps you ought to consider this from more than one edge

Avatar_small
바카라 说:
2024年1月26日 14:58

바카라 바카라사이트 우리카지노 카지노는 바카라, 블랙잭, 룰렛 및 슬롯 등 다양한 게임을 즐기실 수 있는 공간입니다. 게임에서 승리하면 큰 환호와 함께 많은 당첨금을 받을 수 있고, 패배하면 아쉬움과 실망을 느끼게 됩니다.

Avatar_small
하노이 가라오케 说:
2024年1月26日 15:01

하노이 꼭 가봐야 할 베스트 업소 추천 안내 및 예약, 하노이 밤문화 에 대해서 정리해 드립니다. 하노이 가라오케, 하노이 마사지, 하노이 풍선바, 하노이 밤문화를 제대로 즐기시기 바랍니다. 하노이 밤문화 베스트 업소 요약 베스트 업소 추천 및 정리.

Avatar_small
안전놀이터 说:
2024年1月29日 14:12

No.1 먹튀검증 사이트, 먹튀사이트, 검증사이트, 토토사이트, 안전사이트, 메이저사이트, 안전놀이터 정보를 제공하고 있습니다. 먹튀해방으로 여러분들의 자산을 지켜 드리겠습니다. 먹튀검증 전문 커뮤니티 먹튀클린만 믿으세요!!

Avatar_small
베트남 밤문화 说:
2024年1月29日 14:20

베트남 남성전용 커뮤니티❣️ 베트남 하이에나 에서 베트남 밤문화를 추천하여 드립니다. 베트남 가라오케, 베트남 VIP마사지, 베트남 이발관, 베트남 황제투어 남자라면 꼭 한번은 경험 해 봐야할 화끈한 밤문화로 모시겠습니다.

Avatar_small
블록체인개발 说:
2024年4月24日 14:31

블록체인개발 코인지갑개발 IT컨설팅 메스브레인팀이 항상 당신을 도울 준비가 되어 있습니다. 우리는 마음으로 가치를 창조한다는 철학을 바탕으로 일하며, 들인 노력과 시간에 부흥하는 가치만을 받습니다. 고객이 만족하지 않으면 기꺼이 환불해 드립니다.
https://xn--539awa204jj6kpxc0yl.kr/

Avatar_small
IT technology 说:
2024年6月03日 16:34

The tech-original mission is to help you better understand technology, and make better decisions in the fields of IT, Tech, and Crypto.
https://www.tech-original.com/

Avatar_small
IT technology 说:
2024年6月08日 11:48

The tech-original mission is to help you better understand technology, and make better decisions in the fields of IT, Tech, and Crypto.
https://www.tech-original.com/


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter