Comments
yourfanat wrote: I am using another tool for Oracle developers - dbForge Studio for Oracle. This IDE has lots of usefull features, among them: oracle designer, code competion and formatter, query builder, debugger, profiler, erxport/import, reports and many others. The latest version supports Oracle 12C. More information here.
Cloud Expo on Google News
SYS-CON.TV
Cloud Expo & Virtualization 2009 East
PLATINUM SPONSORS:
IBM
Smarter Business Solutions Through Dynamic Infrastructure
IBM
Smarter Insights: How the CIO Becomes a Hero Again
Microsoft
Windows Azure
GOLD SPONSORS:
Appsense
Why VDI?
CA
Maximizing the Business Value of Virtualization in Enterprise and Cloud Computing Environments
ExactTarget
Messaging in the Cloud - Email, SMS and Voice
Freedom OSS
Stairway to the Cloud
Sun
Sun's Incubation Platform: Helping Startups Serve the Enterprise
POWER PANELS:
Cloud Computing & Enterprise IT: Cost & Operational Benefits
How and Why is a Flexible IT Infrastructure the Key To the Future?
Click For 2008 West
Event Webcasts
Frank's Java Code Stack #6 Memory Mapped Files
Frank's Java Code Stack #6 Memory Mapped Files

Don't you guys ever wonder why we get everything late in Java? I can give you many instances like Assertion/DBC, Regular Expressions, Preferences, Non-blocking I/O, and Reference Objects. And the list goes on. In most of the languages, all these techniques were fabricated right from the first release. While this is an issue, which James has to elucidate, let's focus on one such latecomer, "Memory Mapped File", a technique introduced from JDK1.4 for high performance file I/O operations. (Psst?.it's just an implementation of C's mmap( )). Now you can map the content of a file into a ByteBuffer, enabling different threads or processes to work on the buffer directly instead of performing file I/O every time. The changes made in the buffer are reflected in the file.

Code:

1. import java.nio.*;
2. import java.nio.channels.*;
3. import java.io.*;
4.
5. public class mmap{
6. public static void main(String ar[]){
7.
8. try {
9.
10. /* Create a ByteBuffer on a
11. memory-mapped file */
12. File f = new File("test.txt");
13. FileChannel fc = new
14. RandomAccessFile(f,"rw").getChannel();
15.
16. int size=(int)fc.size();
17. MappedByteBuffer buf = fc.map
(FileChannel.MapMode.READ_WRITE,0,size);
18.
19. byte b=(byte)'f';
20. /* Make changes to the Mapped Buffer */
21. buf.put(0, b);
22.
23. /* Force the change to reflect
24. on the file system. It works
25. only when you have opened the
26. channel in READ_WRITE mode */
27. buf.force();
28.
29. /* Close the file channel */
30. fc.close();
31.
32. f = new File("test.txt");
33. fc = new RandomAccessFile
(f, "r").getChannel();
34. /* Let us Map the channel as read only */
35. size=(int)fc.size();
36. buf = fc.map(FileChannel.MapMode.READ_ONLY,0,size);
37.
38. /* Trying to modify a READ_ONLY
39. mapped buffer will throw an Exception */
40. try{
41. /* Will throw ReadOnly Buffer Exception */
42. buf.put(0, b);
43. buf.force();
44. }
45. catch(Exception e){
46. System.out.println(""+e);
47. }
48.
49.
50. /* Closing the channel */
51. fc.close();
52. /* Note that closing the channel
53. has no effect on the Mapped Byte Buffer.
54. buffer still retrieves 'f' */
55.
56. System.out.println(""+(char)buf.get());
57.
58.
59. } catch(Exception e){ }
60.
61. }
62. }

The mapped byte buffer is persistent so even if you close the original channel, the byte buffer can be accessible for reading and not for writing till it gets garbage collected. Also if you open the channel as private (MapMode.PRIVATE), changes made to the resulting buffer will not be proliferated to the file instead, private copies of the modified portions of the buffer will be created. Mapping files to memory increases performance especially if you are reading and writing from larger files. For smaller files, this method is just an overhead.

Assignment:
Map the content of the File channel as a READ_ONLY byte buffer, and try to modify the content of the file using another File object. You'll be surprised!

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

Dear Ulf,
The core strength of Perl is its ability to do search based on common patterns, a direct implementation of Unix's grep conceived during 1970s. Perl uses the same regular expression syntax as the old UNIX grep from its initial release. However, Perl 5 introduced many powerful additions to the regular expression syntax. Regular expressions are an integral part of the Perl language, which has proven to be one of the main reasons why many programmers like to use Perl. And C always had it as regex. U know even lesser know languages like Ruby have an extensive support for Regex. Can u imagine that?:-)

You said "In most of the languages, all these techniques were fabricated right from the first release ...".
Can You tell me one ???
Not even perl had, for instance, regular expression support in its first release ! So, what the hell You are talking about ???

Hey Andrej.
The last argument of the map method takes an int denoting the size of the region to be mapped in the file. We are trying to map the entire content of the file to the Buffer. Thanks for your information, but y would would anyone want to map a non-existent file to the merory? ;-)

Hi Frank,

I have tested your code, but after few tests I have found out that your program returns java.lang.IndexOutOfBoundsException. This exception occurs if the test.txt file does not exist. To correct the error and to show capabilities of NIO when the file does not exist you have to change the line

MappedByteBuffer buf = fc.map(FileChannel.MapMode.READ_WRITE,0,size);

to

MappedByteBuffer buf = fc.map(FileChannel.MapMode.READ_WRITE,0,1);

Size of the MappedByteBuffer should be greater than 0.

Best regards,
Andrej


Your Feedback
Frank Jennings wrote: Dear Ulf, The core strength of Perl is its ability to do search based on common patterns, a direct implementation of Unix's grep conceived during 1970s. Perl uses the same regular expression syntax as the old UNIX grep from its initial release. However, Perl 5 introduced many powerful additions to the regular expression syntax. Regular expressions are an integral part of the Perl language, which has proven to be one of the main reasons why many programmers like to use Perl. And C always had it as regex. U know even lesser know languages like Ruby have an extensive support for Regex. Can u imagine that?:-)
Ulf Pietruschka wrote: You said "In most of the languages, all these techniques were fabricated right from the first release ...". Can You tell me one ??? Not even perl had, for instance, regular expression support in its first release ! So, what the hell You are talking about ???
Frank Jennings wrote: Hey Andrej. The last argument of the map method takes an int denoting the size of the region to be mapped in the file. We are trying to map the entire content of the file to the Buffer. Thanks for your information, but y would would anyone want to map a non-existent file to the merory? ;-)
Andrej wrote: Hi Frank, I have tested your code, but after few tests I have found out that your program returns java.lang.IndexOutOfBoundsException. This exception occurs if the test.txt file does not exist. To correct the error and to show capabilities of NIO when the file does not exist you have to change the line MappedByteBuffer buf = fc.map(FileChannel.MapMode.READ_WRITE,0,size); to MappedByteBuffer buf = fc.map(FileChannel.MapMode.READ_WRITE,0,1); Size of the MappedByteBuffer should be greater than 0. Best regards, Andrej
Latest Cloud Developer Stories
"ZeroStack is a startup in Silicon Valley. We're solving a very interesting problem around bringing public cloud convenience with private cloud control for enterprises and mid-size companies," explained Kamesh Pemmaraju, VP of Product Management at ZeroStack, in this SYS-CON.tv i...
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Sen...
"Codigm is based on the cloud and we are here to explore marketing opportunities in America. Our mission is to make an ecosystem of the SW environment that anyone can understand, learn, teach, and develop the SW on the cloud," explained Sung Tae Ryu, CEO of Codigm, in this SYS-CO...
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them ...
"There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, in this SY...
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021



SYS-CON Featured Whitepapers
ADS BY GOOGLE