Memory-mapped files in java tutorial with example . File I/O vs Memory-Mapped Files tutorial

The following tutorial covers about what is memory mapped files and  what are the advantages and drawbacks of using Memory-Mapped Files and also covers that how to map a  file into memory with example code.
 Any files can be accessed using  

1.  Simple  File I/O
 2.  Memory-Mapped Files

Some of  the drawbacks of Simple File I/O  (Usual  read() and write()) is as follows.

 When an  application requires to read data from outside  such as   file data  on disk (outside of virtual  / process  address space)  ,  system call to usual file I/O functions (e.g., read() and write() subroutines )  , copies the file data to intermediate buffer  . Then the data is transferred  to the physical file or the process .  This  Intermediate buffering is slow and expensive which reduces the I/O performance.
 The alternative mechanishm is Memory mapped files . Memory mapped files provide a mechanism  to map the  file data  into the area of Virtual Memory (process address space) .   This enables an application, including multiple processes, to read and write  the file data directly to the memory  without performing any explicit file read or write operations on the physical file .   When we access a  part of the file which is  not  in  memory, it will be automatically paged in  by  the  OS.  Subsequent reads / writes to / from that page are treated as ordinary memory accesses .  There is no separation between modifying the data and saving it to a disk.

Some of the benefits using  Memory mapped files ( Accessing a data directly from main memory )
 1. Eliminate intermediary buffering

2. Increases I/O performance

3. More than one processes can map the same file  i.e  pages in memory can be be shared among the processes which saves memory space and  supports inter-process communications

4. supports  lazy loading i.e   the process of allocating and loading pages in main memory  must be deferred as long as possible . The page is loaded into RAM when the page is actually needed .   You don't need to have memory for the entire file.  This helps  to read  a large file with small amount of RAM

5. File data can be accessed and modified with out having to execute any explicit I/O operations  on the file.

6. Reading / Writing  large files this is often  more efficient than invoking the usual read or write methods.

      Mapping a file into memory is implemented by a FileChannel object that  is packaged with java.nio   which is available from JDK 1.4 .   The map() method of a FileChannel object  maps to  a portion or all of channel’s file  into memory  and  returns a reference to a buffer of type MappedByteBuffer .

 Syntax for the map() method is
 public abstract MappedByteBuffer map(FileChannel.MapMode mode,      long position,  long size)       throws IOException
              - Maps a region of this channel's file directly into memory.   The map() method returns a MappedByteBuffer, which is a subclass of ByteBuffer. Methods of ByteBuffer can be used with MappedByteBuffer class . 
 A region of a file may be mapped into memory in one of the following three modes:
 1. MapMode.READ_ONLY - Can not modify the resulting buffer
 2. MapMode.READ_WRITE - Can change the resulting buffer
 3. MapMode.PRIVATE  -  creates a private copies of the modified portions of the buffer  which is  not  visible to other processes hat have mapped the same file.  Modification to the resulting buffer will not be reproduced to the file

The following line of code maps the first 1024 bytes of a file into memory in Read / write mode. 

MappedByteBuffer mbb = fc.map( FileChannel.MapMode.READ_WRITE, 0, 1024 );

To map the entire file specify the start file position as zero, and the length that is mapped as the length of the file.

MappedByteBuffer mbb= fc.map(READ_WRITE, 0L,fc.size()).load();

The buffer is created with the READ_WRITE mode, which permits the buffer to be accessed or modified and maps to the entire file.  The map() method returns a reference to the MappedByteBuffer object
 Drawbacks of  Memory mapped files

                 1.  Wastage of memory for small files .  In Memory mapped files , disk block is mapped  to a page   in memory . The size of the  page  is usually  4 KB  . To map a  file  with size of 9 KB , 3 pages are allocated with total size of 12 KB in Memory.  3 KB   memory is wasted.

                 2. When a requested page is not in the main memory , page fault occurs which reduces performance.

                3. Another limitation is Maping  of file contents in memory depends on available Virtual Address Space.   32 bit OS gets a set of virtual memory addresses from 0 to 4,294,967,295 (2*32-1 = 4 GB) .
 Now let us see the code example of Maemory Mapped Files . I have written two programs  to read a large log file  using the Standard File IO and Memory-mapped I/O  and you can run the two programs to get the time taken to read the given big log files by Standard File IO and Memory-mapped I/O . Obviously , Reading large file using Memory-mapped I/O  is faster than using Standard File IO.

Using Memory-mapped I/O
  

 

import java.io.FileInputStream;

import java.io.*;

import java.nio.MappedByteBuffer;

import java.nio.channels.FileChannel;

public class MemoryMappedIO1 {

    public static void main(String[] args) {

        long tm = 0;


        FileInputStream fis = null;


        try {




           fis = new FileInputStream("CBS.log");


            int len=1024;


            byte[] buf = new byte[len];



            tm = System.currentTimeMillis();




            FileChannel fc = fis.getChannel();




            MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());




            while (mbb.hasRemaining()) {



 if (len>mbb.remaining())




 mbb.get(buf,0,mbb.remaining());




 else




 mbb.get(buf,0,len);



//System.out.println(new String(buf));


            }




            System.out.printf("Time to read file TestLog.log: %d ms\n", (System.currentTimeMillis()-

tm));




        }




        catch (Exception ex) {




            ex.printStackTrace(System.err);




        }




        finally {




            if (fis != null) {




                try {




                    fis.close();




                }




                catch (Exception ex) {




                }




            }




        }




    }




}



Using Standard File IO:
   

 

import java.io.BufferedReader;




import java.io.*;




public class StandardBufferedIO1 {


    public static void main(String[] args) {


        long ts, te = 0;

         InputStream in = null;


        try {


    in=new FileInputStream("CBS.log");


            ts = System.currentTimeMillis();


      byte[] buf = new byte[1024];


    int len;

    while ((len = in.read(buf)) !=-1) {


 //System.out.println(new String(buf));


      //  out.write(buf, 0, len);


    }


              te=System.currentTimeMillis();


            System.out.printf("Time taken to read log file  %d ms\n", (te-ts));


        }




        catch (Exception e) {


            e.printStackTrace(System.err);


        }


        finally {




            if (in!= null) {




                try {


                  in.close();


                }


                catch (Exception e) {e.printStackTrace(System.err);    }


            }


        }


    }


}

Apache ofbiz tutorial : how to change ofbiz's administrator login password

To change administrator login password apply below step :

If you are the OFBiz administrator and you forget this user's password, you could be out of luck
since the administrator (the "admin" user login) has all the privileges necessary to perform
any OFBiz task, including logging in and assigning the admin user a new password.
If you find yourself in this situation, there is no easy way to retrieve this password such that
you may use it to log in. The only solution to this problem is to reset the password by directly
manipulating the correct entity in the database, or let OFBiz do that for you using the
following recipe.
Getting ready
Before following this recipe, ensure these steps are performed:
1. Navigate to the OFBiz install directory.
2. Open a command line or console window.
3. If you are running OFBiz, it is best to stop it at this time.

To reset the admin password, follow these steps:
1. From the OFBiz install directory, run the following command:
ant load-admin-user-login -DuserLoginId=admin
2. Restart OFBiz.
3. Log in to OFBiz as the admin user where the login user name is "admin" and the
password is "ofbiz".
4. When prompted to change the admin user's password, enter the new password or
"ofbiz" to maintain the existing value.

How to change JavaScript fuction call name submitFormDisableSubmits in Apache ofbiz minilang form onSubmit event

When i  am using minilang form it is always call submitFormDisableSubmits() javaScript function on onSubmit event 

we can change it by following way

apache use HtmlFormMacroLibrary.ftl where you can change the function name submitFormDisableSubmits according to you

How to use own JavaScript file in Apache ofbiz | implement own JavaScript function call in Apache ofbiz

In my Apache ofbiz project i have implemented own JavaScript in Minilang code

1. Add below line of code to give reference of JavaScript File in ogbiz Screen


           <actions>
                <set field="titleProperty" value="ProductFindFacilities"/>
                <set field="headerItem" value="facility"/>
                <set field="layoutSettings.javaScripts[+0]" value="/images/TestJavaScript.js" global="true"/>
            </actions>

2. by using Event and Action attribute as below to call javascript function from minilang form code

<field name="submitButton" title="Get Inventory Feed" widget-style="smallSubmit" event="onclick" action="javascript:return submitFormEnableButtonByNameTest(this,submitButton)">
                                                <submit button-type="submit" />

event  > it use for write javaScript event like onClick, onMouseOver etc
action > use for call funtion name of JavaScript

How to Reboot remote computers on a domain

Below Step to reboot remote computers
arrComputer = Array("Computer1", "Computer2", "Computer3")
For Each strComputer In arrComputer
Set objWMIService = GetObject ("winmgmts:{impersonationLevel=impersonate,(Shutdown)}\\" & strComputer & "\root\cimv2")
Set colOperatingSystems = objWMIService.ExecQuery ("Select * from Win32_OperatingSystem")

For Each objOperatingSystem in colOperatingSystems
objOperatingSystem.Reboot(2)
Next
Next

Builder Design pattern in Java ? GoF design pattern

Builder design pattern in Java is a creational pattern i.e. used to create objects, similar to factory method design pattern which is also creational design pattern. Before learning any design pattern I suggest find out the problem a particular design pattern solves. Its been well said necessity is mother on invention. learning design pattern without facing problem is not that effective, Instead if you have already faced issues than its much easier to understand design pattern and learn how its solve the issue. In this Java design pattern tutorial we will first see what problem Builder design pattern solves which will give some insight on when to use builder design pattern in Java, which is also a popular design pattern interview question and then we will see example of Builder design pattern and pros and cons of using Builder pattern in Java.

What problem Builder pattern solves in Java
What is builder design pattern in Java with exampleAs I said earlier Builder pattern is a creational design pattern it means its solves problem related to object creation. Constructors in Java are used to create object and can take parameters required to create object. Problem starts when an Object can be created with lot of parameters, some of them may be mandatory and others may be optional. Consider a class which is used to create Cake, now you need number of item like egg, milk, flour to create cake. many of them are mandatory and some  of them are optional like cherry, fruits etc. If we are going to have overloaded constructor for different kind of cake then there will be many constructor and even worst they will accept many parameter.

Problems:
1) too many constructors to maintain.
2) error prone because many fields has same type e.g. sugar and and butter are in cups so instead of 2 cup sugar if you pass 2 cup butter, your compiler will not complain but will get a buttery cake with almost no sugar with high cost of wasting butter.

You can partially solve this problem by creating Cake and then adding ingredients but that will impose another problem of leaving Object on inconsistent state during building, ideally cake should not be available until its created. Both of these problem can be solved by using Builder design pattern in Java. Builder design pattern not only improves readability but also reduces chance of error by adding ingredients explicitly and making object available once fully constructed.

By the way there are many design pattern tutorial already there in Javarevisited like Decorator pattern tutorial and  Observer pattern in Java. If you haven’t read them already then its worth looking.

Example of Builder Design pattern in Java
We will use same example of creating Cake using Builder design pattern in Java. here we have static nested builder class inside Cake which is used to create object.

Guidelines for Builder design pattern in Java
1) Make a static nested class called Builder inside the class whose object will be build by Builder. In this example its Cake.

2) Builder class will have exactly same set of fields as original class.
3) Builder class will expose method for adding ingredients e.g. sugar() in this example. each method will return same Builder object. Builder will be enriched with each method call.

4) Builder.build() method will copy all builder field values into actual class and return object of Item class.
5) Item class (class for which we are creating Builder) should have private constructor to create its object from build() method and prevent outsider to access its constructor.

public class BuilderPatternExample {

    public static void main(String args[]) {
    
        //Creating object using Builder pattern in java
        Cake whiteCake = new Cake.Builder().sugar(1).butter(0.5).  eggs(2).vanila(2).flour(1.5). bakingpowder(0.75).milk(0.5).build();
    
        //Cake is ready to eat :)
        System.out.println(whiteCake);
    }
}

class Cake {

    private final double sugar;   //cup
    private final double butter;  //cup
    private final int eggs;
    private final int vanila;     //spoon
    private final double flour;   //cup
    private final double bakingpowder; //spoon
    private final double milk;  //cup
    private final int cherry;

    public static class Builder {

        private double sugar;   //cup
        private double butter;  //cup
        private int eggs;
        private int vanila;     //spoon
        private double flour;   //cup
        private double bakingpowder; //spoon
        private double milk;  //cup
        private int cherry;

        //builder methods for setting property
        public Builder sugar(double cup){this.sugar = cup; return this; }
        public Builder butter(double cup){this.butter = cup; return this; }
        public Builder eggs(int number){this.eggs = number; return this; }
        public Builder vanila(int spoon){this.vanila = spoon; return this; }
        public Builder flour(double cup){this.flour = cup; return this; }
        public Builder bakingpowder(double spoon){this.sugar = spoon; return this; }
        public Builder milk(double cup){this.milk = cup; return this; }
        public Builder cherry(int number){this.cherry = number; return this; }
    
    
        //return fully build object
        public Cake build() {
            return new Cake(this);
        }
    }

    //private constructor to enforce object creation through builder
    private Cake(Builder builder) {
        this.sugar = builder.sugar;
        this.butter = builder.butter;
        this.eggs = builder.eggs;
        this.vanila = builder.vanila;
        this.flour = builder.flour;
        this.bakingpowder = builder.bakingpowder;
        this.milk = builder.milk;
        this.cherry = builder.cherry;     
    }

    @Override
    public String toString() {
        return "Cake{" + "sugar=" + sugar + ", butter=" + butter + ", eggs=" + eggs + ", vanila=" + vanila + ", flour=" + flour + ", bakingpowder=" + bakingpowder + ", milk=" + milk + ", cherry=" + cherry + '}';

    }

}

Output:
Cake{sugar=0.75, butter=0.5, eggs=2, vanila=2, flour=1.5, bakingpowder=0.0, milk=0.5, cherry=0}


Builder design pattern in Java – Pros and Cons

Live everything Builder pattern also has some disadvantages, but if you look at below, advantages clearly outnumber disadvantages of Builder design pattern. Any way here are few advantages and disadvantage of Builder design pattern for creating objects in Java.

Advantages:
1) more maintainable if number of fields required to create object is more than 4 or 5.
2) less error-prone as user will know what they are passing because of explicit method call.
3) more robust as only fully constructed object will be available to client.

Disadvantages:
1) verbose and code duplication as Builder needs to copy all fields from Original or Item class.

When to use Builder Design pattern in Java
Builder Design pattern is a creational pattern and should be used when number of parameter required in constructor is more than manageable usually 4 or at most 5. Don't confuse with Builder and Factory pattern there is an obvious difference between Builder and Factory pattern, as Factory can be used to create different implementation of same interface but Builder is tied up with its Container class and only returns object of Outer class.

That's all on Builder design pattern in Java. we have seen why we need Builder pattern , what problem it solves, Example of builder design pattern in Java and finally when to use Builder patter with pros and cons. So if you are not using telescoping constructor pattern or have a choice not to use it than Builder pattern is way to go

xargs command example in Linux - Unix tutorial

xargs command in unix or Linux is a powerful command used in conjunction with find and grep command in UNIX to divide a big list of arguments into small list received from standard input. find and grep command produce long list of file names and we often want to either remove them or do some operation on them but many unix operating system doesn't accept such a long list of argument. UNIX xargs command divide that list into sub-list with acceptable length and made it work. This Unix tutorial is in continuation of my earlier post on Unix like 10 examples of chmod command in Unix and How to update soft link in Linux. If you haven’t read those unit tutorial than check them out. By the way In this tutorial we will see different example of unix xargs command to learn how to use xargs command with find and grep and other unix command and make most of it. Though what you can do with xargs in unix can also be done by using options provided in find but believe xargs is much easy and powerful.

Unix Xargs command example
Following is list of examples of xargs command which shows how useful knowledge of xargs can be. Feel free to copy and use this command and let me know if it didn’t work in any specific Unix operating system like AIX or Solaris.

Xargs Example 1- with and without xargs
in this example of xargs command we will see how output changes with use of xargs command in unix or Linux. Here is the output of find command without xargs first and than with xargs, you can clearly see that multiline output is converted into single line:

devuser@system:/etc find . -name "*bash*"
./bash.bashrc
./bash.bash_logout
./defaults/etc/bash.bashrc
./defaults/etc/bash.bash_logout
./defaults/etc/skel/.bashrc
./defaults/etc/skel/.bash_profile
./postinstall/bash.sh.done
./setup/bash.lst.gz
./skel/.bashrc
./skel/.bash_profile

devuser@system:/etc find . -name "*bash*" | xargs
./bash.bashrc ./bash.bash_logout ./defaults/etc/bash.bashrc ./defaults/etc/bash.bash_logout ./defaults/etc/skel/.bashrc ./defaults/etc/skel/.bash_profile ./postinstall/bash.sh.done ./setup/bash.lst.gz ./skel/.bashrc ./skel/.bash_profile


Xargs Example 2 – xargs and grep
Another common use fo unix xargs command is to first find the files and then look for specific keyword on that file using grep command. here is an example of xargs command that does it

find . -name "*.java" | xargs grep "Stock"

This will first find all java files from current directory or below and than on each java file look for word "Stocks"if you have your development environment setup in Linux or unix this is a great tool to find function references or class references on java files.

Xargs Example 3 – delete temporary file using find and xargs
Another common example of xargs command in unix is removing temporary files from system.

find /tmp -name "*.tmp" | xargs rm

This will remove all .tmp file from /tmp or below directory. xargs in unix is very fast as compared to deleting single file at a time which can also be done by using find command alone. By the way this is also a very popular Unix interview question.

Xargs Example 4 – xargs -0 to handle space in file name
xargs command examples in Unix and Linux - TutorialAbove example of xargs command in unix will not work as expected if any of file name contains space or new line on it. to avoid this problem we use find -print0 to produce null separated file name and xargs-0 to handle null separated items. Here is an example of xargs command in unix which can handle file name with spaces and newline:

find /tmp -name "*.tmp" -print0 | xargs -0 rm

Xargs Example 5 – xargs and cut command in Unix
Though most of xargs examples in unix will be along with find and grep command but xargs is not just limited to this two it can also be used with any command which generated long list of input for example we can use xargs with cut command in unix. In below example of unix xargs we will xargs example with cut command. for using cut command let's first create a .csv file with some data e.g.

devuser@system:/etc cat smartphones.csv
Iphone,Iphone4S
Samsung,Galaxy
LG,Optimus
HTC,3D

Now we will display name of mobile companies from first column using xargs command in one line:

devuser@system:/etc cut -d, -f1 smartphones.csv | sort | xargs
HTC Iphone LG Samsung

xargs Example 6 – command convert muti line output into single line
One more common example of xargs commands in Linux is by converting output of one command into one line. For example you can run any command and then combine xargs to convert output into single line. here is an example xargs in unix which does that.

devuser@system:~/perl ls -1 *.txt
derivatives.txt
futures.txt
fx.txt
options.txt
stock.txt
swaps.txt

devuser@system:~/perl ls -1 *.txt | xargs
derivatives.txt futures.txt fx.txt options.txt stock.txt swaps.txt


Xargs Example 7 - Counting number of lines in each file using xargs and find.
In this example of xargs command in unix we will combine "wc" with xargs and find to count number of lines in each  file, just like we did in our previous example with grep where we tried to find specific word in each Java file.

devuser@system:~/perl ls -1 *.txt | xargs wc -l
  0 derivatives.txt
  2 futures.txt
  0 fx.txt
  1 options.txt
  3 stock.txt
  0 swaps.txt

Xargs command Example 7 - Passing subset of arguments to xargs in Linux.
Some commands in unix can only work at certain number of argument e.g. diff command needs two argument. when used with xargs you can use flag "-n" to instruct xargs on how many argument it should pass to given command. this xargs command line option is extremely useful on certain situation like repeatedly doing diff etc. xargs in unix or Linux will continue to pass argument in specified number until it exhaust all input. here is an example of unix xargs command with limited argument:

devuser@system:~/perl ls -1 *.txt | xargs -n 2 echo
derivatives.txt futures.txt
fx.txt options.txt
stock.txt swaps.txt

In this example,  xargs is passing just two files at a time to echo as specified with "-n 2" xargs command line option.

Xargs example 9 - avoid "Argument list too long"
xargs in unix or Linux was initially use to avoid "Argument list too long" errors and by using xargs you send sub-list to any command which is shorter than "ARG_MAX" and that's how xargs avoid "Argument list too long" error. You can see current value of "ARG_MAX" by using getconf ARG_MAX. Normally xargs own limit is much smaller than what modern system can allow, default is 4096. You can override xargs sub list limit by using "-s" command line option.

Xargs Example 10 – find –exec vs find + xargs
xargs with find command is much faster than using -exec on find. since -exec runs for each file while xargs operates on sub-list level. to give an example if you need to change permission of 10000 files xargs with find will be almost 10K time faster than find with -exec because xargs change permission of all file at once. For more examples of find and xargs see my post 10 frequently used find command examples in Linux


Important points on xargs command in Unix and Linux
Now let’s revise some important points about xargs command in Unix which is worth remembering :

1. An important point to note about xargs is that it doesn't handle files which has newlines or white space in its name and to avoid this problem one should always use "xargs -0". xargs -o change separator to null character so its important that input feed to xargs is also use null as separator. for example gnu find command use -print0 to produce null separated file names.

2. Xargs command receives command from standard input which is by default separated with space or newlines and
execute those commands, you can still use double quotes or single quote to group commands.

3. If you don't give any command to xargs in unix, default command executed by xargs is /bin/echo and it will simply display file names.

4. One rare problem with xargs is end of file string, by default end of file string is "_" and if this string occurs in input the rest of input is ignored by xargs. Though you can change end of file string by using option "-eof".

5. Use man xargs or xargs --help to get help on xargs online while working in unix or Linux.

In short xargs command in Unix or Linux is an essential tool which enhances functionality of front line commands like find, grep or cut and gives more power to your shell script. These xargs command examples are good start for anyone wants to learn more about xargs command.Though these xargs examples are tested in Linux environment they will applicable for other Unix systems likes Solaris or AIX also. let us know if you face any issue while using these examples.