Monday 31 March 2014

How can you improve Java I/O performance?

Java applications that utilise Input/Output are excellent candidates for performance  tuning. Profiling of Java applications that handle significant volumes of data will show significant time spent in I/O operations. This means substantial gains can be had from I/O performance tuning. Therefore, I/O efficiency should be a high priority for developers looking to optimally increase performance.
The basic rules for speeding up I/O performance are
  • Minimise accessing the hard disk.
  • Minimise accessing the underlying operating system.
  • Minimise processing bytes and characters individually.   
Let us look at some of the techniques to improve I/O performance.

Use bufferingto minimise disk access and underlying operating system. As shown below, with buffering large chunks of a file are read from a disk and then accessed a byte or character at a time.

Without buffering : inefficient code
try{
File f = new File("myFile.txt");
FileInputStream fis = new FileInputStream(f);
int count = 0;
int b = ;
while((b = fis.read()) != -1){
if(b== '\n') {
count++;
}
}
// fis should be closed in a finally block.
fis.close() ;
}
catch(IOException io){}
Note: fis.read() is a native method call to the underlying system.
With Buffering:yields better performance
try{
File f = new File("myFile.txt");
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
int count = 0;
int b = ;
while((b = bis.read()) != -1){
if(b== '\n') {
count++;
}
}
//bis should be closed in a finally block.
bis.close() ;
}
catch(IOException io){}
Note:bis.read() takes the next byte from the input buffer and only
rarely access the underlying operating system.

Instead of reading a character or a byte at a time, the above code with buffering can be improved further by reading one line at a time as shown below:

FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
While (br.readLine() != null) count++;

Sunday 16 March 2014

How Volatile in Java works ?

What  is Volatile variable in Java  and when to use Volatile variable in Java is famous multi-threading interview question in Java interviews.
apart from use in multitreaded programming it is also used for optimization.
When Compiler compiles a program it performs some sort of optimization in it.
if a variable is decleard to be volatile then compiler does't perform any  optimization on it

When to use Volatile variable in Java

1) You can use Volatile variable if you want to read and write long and double variable atomically. long and double both are 64 bit data type and by default writing of long and double is not atomic and platform dependence. Many  platform perform write in long and double variable 2 step, writing 32 bit in each step, due to this its possible for a Thread to see 32 bit from two different write. You can avoid this issue by making long and double variable volatile in Java.
2) Volatile variable can be used as an alternative way of achieving synchronization in Java in some cases, like Visibility. with volatile variable its guaranteed that all reader thread will see updated value of volatile variable once write operation  completed, without volatile keyword different reader thread may see different values.
3) volatile variable can be used to inform compiler that a particular field is subject to be accessed by multiple threads, which will prevent compiler from doing any reordering or any kind of optimization which is not desirable in multi-threaded environment. Without volatile variable compiler can re-order code, free to cache value of volatile variable instead of always reading from main memory. like following example without volatile variable may result in infinite loop
4) Another place where volatile variable can be used is to fixing double checked locking in Singleton pattern. As we discussed in Why should you use Enum as Singleton that double checked locking was broken in Java 1.4 environment.
 

Friday 7 March 2014

Why are GUIs Single-threaded?

In the old days, GUI applications were single-threaded and GUI events were processed from a "main event loop". Modern GUI frameworks use a model that is only slightly different: they create dedicated event dispatch thread (EDT) for handling GUI events.

Single-threaded GUI frameworks are not unique to Java; Qt, NextStep, MacOS Cocoa, X Windows, and many others are also single-threaded. This is not for lack of trying; there have been many attempts to write multithreaded GUI frameworks, but because of persistent problems with race conditions and deadlock, they all eventually arrived at the single-threaded event queue model in which a dedicated thread fetches events off a queue and dispatches them to applicationdefined event handlers. (AWT originally tried to support a greater degree of multithreaded access, and the decision to make Swing single-threaded was based largely on experience with AWT.)

Multithreaded GUI frameworks tend to be particularly susceptible to deadlock, partially because of the unfortunate interaction between input event processing and any sensible object-oriented modeling of GUI components.

Another factor leading to deadlock in multithreaded GUI frameworks is the prevalence of the
model-view-control (MVC) pattern. Factoring user interactions into cooperating model, view, and controller objects greatly simplifies implementing GUI applications, but again raises the risk of inconsistent lock ordering. The controller calls into the model, which notifies the view that something has changed. But the controller can also call into the view, which may in turn call back into the model to query the model state. The result is again inconsistent lock ordering, with the attendant risk of deadlock.

Java ArrayList Tutorial

It’s also important to remember that ArrayList is not synchronized and should not be shared between multiple threads. If multiple threads access a Java ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (As per Java doc a structural modification is any operation that adds or deletes one or more elements, or explicitly re-sizes the backing array; merely setting the value of an element is not a structural modification.)


1) Creating an ArrayList
You can use ArrayList in Java with or without Generics both are permitted by generics version is recommended because of enhanced type-safety.
In this example we will create an ArrayList of String in Java. This Java ArrayList will only allow String and will throw compilation error if we try to any other object than String.

ArrayList<String> stringList = new ArrayList<String>(); //Generic ArrayList to Store only String objects
2) Putting an Item into ArrayList
Second line will result in compilation error because this Java ArrayList will only allow String elements.
stringList.add("Item"); //no error because we are storing String
stringList.add(new Integer(2)); //compilation error
3) Checking size of ArrayList
Size of an ArrayList in Java is total number of elements currently stored in ArrayList.

int size = stringList.size();

4) Checking Index of an Item in Java Arraylist
You can use indexOf() method of ArrayList in Java to find out index of a particular object.

int index = stringList.indexOf("Item"); //location of Item object in List
5) Retrieving Item from arrayList in a loop
Many a times we need to traverse on Java ArrayList and perform some operations on each retrieved item. Here are two ways of doing it without using Iterator. We will see use of Iterator in next section.
for (int i = 0; i < stringList.size(); i++)
   String item = stringList.
get(i);
   System.
out.println("Item " + i + " : " + item);
}

From Java
5 onwards you can use foreach loop as well

for(String item: stringList){
System.
out.println("retrieved element: " + item);
}
6) Checking ArrayList for an Item
Sometimes we need to check whether an element exists in ArrayList in Java or not for this purpose we can use contains () method of Java. contains() method takes type of object defined in ArrayList creation and returns true if this list contains the specified element.
7) Checking if ArrayList is Empty
We can use isEmpty() method of Java ArrayList to check whether ArrayList is empty. isEmpty() method returns true if this ArrayList contains no elements. You can also use size() method of List to check if List is empty
boolean result = stringList.isEmpty(); //isEmpty() will return true if List is empty

if(stringList.size() == 0){
   System.
out.println("ArrayList is empty");
}

8) Removing an Item from ArrayList
There are two ways to remove any elements from ArrayList in Java. You can either remove an element based on its index or by providing object itself. Remove remove (int index) and remove (Object o) method is used to remove any element from ArrayList in Java. Since ArrayList allows duplicate its worth noting that remove (Object o) removes the first occurrence of the specified element from this list, if it is present. In below code first call will remove first element from ArrayList while second call will remove first occurrence of item from ArrayList in Java.
stringList.remove(0);  
stringList.remove(item);

9) Copying data from one ArrayList to another ArrayList in Java
Many a times you need to create a copy of ArrayList for this purpose you can use addAll(Collection c) method of ArrayList in Java to copy all elements from on ArrayList to another ArrayList in Java. Below code will add all elements of stringList to newly created copyOfStringList.
ArrayList<String> copyOfStringList = new ArrayList<String>();
copyOfStringList.
addAll(stringList);

10) Replacing an element at a particular index
You can use set (int index, E element) method of java ArrayList to replace any element from a particular index. Below code will replace first element of stringList from "Item" to "Item2".

stringList.set(0,"Item2");

11) Clearing all data from ArrayList
ArrayList in Java provides clear () method which removes all of the elements from this list. Below code will remote all elements from our stringList and make the list empty. You can reuse Java ArrayList after clearing it.

stingList.clear();

12) Converting from ArrayList to Array in Java
Java ArrayList provides you facility to get the array back from your ArrayList. You can use toArray(T[] a) method returns an array containing all of the elements in this list in proper sequence (from first to last element). "a" is the array into which the elements of the list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
String[] itemArray = new String[stringList.size()];
String
[] returnedArray = stringList.toArray(itemArray);

13) Creating Synchronized ArrayList
Some times you need to synchronize your ArrayList in java to make it shareable between multiple threads you can use Collections utility class for this purpose as shown below.

List list = Collections.synchronizedList(new ArrayList(...));
14) Creating ArrayList from Array in Java
ArrayList in Java is amazing you can create even an ArrayList full of your element from an already existing array. You need to use Arrays.asList(T... a)  method for this purpose which returns a fixed-size list backed by the specified array.

ArrayList stringList = Arrays.asList(new String[]{"One", "Two", "Three"); //this is not read only List you can still update value of existing elements

15) Traversing in ArrayList in Java
You can use either Iterator or ListIterator for traversing on Java ArrayList. ListIterator will allow you to traverse in both directions while both Iterator and ListIterator will allow you to remove elements from ArrayList in Java while traversing.
Iterator itr = stringList.iterator();
while(itr.hasNext()){
System.
out.println(itr.next());
}

ListIterator listItr = stringList.
listIterator();
while(listItr.hasNext()){
System.
out.println(itr.next());
}

Why character array is better than String for Storing password in Java ?

1) Since Strings are immutable in Java if you store password as plain text it will be available in memory until Garbage collector clears it and since String are used in String pool for reusability there is pretty high chance that it will be remain in memory for long duration, which pose a security threat. Since any one who has access to memory dump can find the password in clear text and that's another reason you should always used an encrypted password than plain text. Since Strings are immutable there is no way contents of Strings can be changed because any change will produce new String, while if you char[] you can still set all his element as blank or zero. So Storing password in character array clearly mitigates security risk of stealing password.
2) Java itself recommends using getPassword() method of JPasswordField which returns a char[] and deprecated getText() method which returns password in clear text stating security reason. Its good to follow advice from Java team and adhering to standard rather than going against it.
3) With String there is always a risk of printing plain text in log file or console but if use Array you won't print contents of array instead its memory location get printed. though not a real reason but still make sense.

String strPassword="Unknown";
char[] charPassword= new char[]{'U','n','k','w','o','n'};
System.out.println("String password: " + strPassword);
System.out.println("Character password: " + charPassword);

String password: Unknown
Character password: [C@110b053

Thursday 6 March 2014

How to Find IP address of Localhost, Server or Your Machine

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;

/*
 * @author Pandey
 */
public class IPAddress {

    public static void main(String args[]) {

        // First get InetAddress for the machine, here localhost
        InetAddress myIP = null;
        try {
            myIP = InetAddress.getLocalHost();

        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // getHostAddress() returns IP address of a machine
        String IPAddress = myIP.getHostAddress();

        // getHostname returns DNS hostname of a machine
        String hostname = myIP.getHostName();

        System.out.printf("IP address of Localhost is %s %n", IPAddress);
        System.out.printf("Host name of your machine is %s %n", hostname);

    }

}

Output:
IP address of Localhost is 192.168.1.41
Host name of your machine is Jaachase

Java interview question: Why Strings are immutable?

Lets start with immutability itself. An immutable object is an object which state is guaranteed to stay identical over its entire lifetime. This is really a good definition. Isn’t it? It means that the state of object once initialized, can never be changed anyhow.
Normally immutability in java is achieved through following steps :
  1. Don’t provide mutator methods for any field
  2. Make all fields final and private
  3. Don’t allow subclasses by declaring the class final itself
  4. Return deep cloned objects with copied content for all mutable fields in class 

1) Security : The first and undeniably most important reason is security. Well, its not only about your application, but even for JDK itself. Java class loading mechanism works on class names passed as parameters, then these classes are searched in class path. Imagine for a minute, Strings were mutable, then anybody could have injected its own class-loading mechanism with very little effort and destroyed or hacked in any application in a minute.
[ Well, I think in this case java didn't have got any popularity today... :-) and nobody would be using it]. It means Strings were immutable that’s why java is still around in the game.
2) Performance : I believe that it is not the immutability of String class that gives it performance, rather it is string pool which works silently behind the scene. But at the same time, string pool is not a possibility without making String class immutable. So, it all again comes down to immutability of String class which allowed string pools, and thus better performance.
3) Thread safety: Immutable objects are safe when shared between multiple threads in multi-threaded applications. Just understand and learn it. There is no super logic. If something can’t be changed, then even thread can not change it.
As String class is main building block of java programming language, because of its use in class loading mechanism, it was indeed a must use case to prevent the String class from being dirty in case of multiple thread. Immutability does the magic here.
I think its enough reasoning to satisfy the need of interviewer. If after these explanations he is not satisfied, he never will be