Saturday 21 July 2012

Try-With-Resources In JDK 7

In Java, normally we open a file in a try block, and close the file in the finally block, see following :

try{
  //open file or resources
}catch(IOException){
  //handle exception
}finally{
  //close file or resources
}
In JDK 7, a new “try-with-resources” approach is introduced. When a try block is end, it will close or release your opened file automatically.
try(open file or resource here){
 //...
}
//after try block, file will close automatically.
In JDK 6:
package com.sanjeetpaney.io;
 
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
 
public class Example1 {
 
 public static void main(String[] args) {
 
  BufferedReader br = null;
 
  try {
 
   String line;
 
   br = new BufferedReader(new FileReader("C:\\testing.txt"));
 
   while ((line = br.readLine()) != null) {
    System.out.println(line);
   }
 
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if (br != null)br.close();
   } catch (IOException ex) {
    ex.printStackTrace();
   }
  }
 
 }
}
In JDK 7:
package com.sanjeetpandey.io;
 
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
 
public class Example2 {
 
 public static void main(String[] args) {
 
  try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
  {
 
   String line;
 
   while ((line = br.readLine()) != null) {
    System.out.println(line);
   }
 
  } catch (IOException e) {
   e.printStackTrace();
  } 
 
 }
}

Tuesday 17 July 2012

How to get free Disk Space in Java

In Java old days, it really difficult to determine the free disk space on a partition of local system. But now this is changed since JDK 1.6 released, a few new methods like getTotalSpace(), getUsableSpace() and getFreeSpace(), are bundled with java.io.File to retrieve the partition or disk space detail.

package com.sanjeetpandey.core;
 
import java.io.File;
 
public class DiskSpaceDetail
{
    public static void main(String[] args)
    { 
     File file = new File("c:");
     long totalSpace = file.getTotalSpace(); //total disk space in bytes.
     long usableSpace = file.getUsableSpace(); //allocated / free disk space in bytes.
     long freeSpace = file.getFreeSpace(); //unallocated / free disk space in bytes.
 
     System.out.println(" === Partition Detail ===");
 
     System.out.println(" === bytes ===");
     System.out.println("Total size : " + totalSpace + " bytes");
     System.out.println("Space free : " + usableSpace + " bytes");
     System.out.println("Space free : " + freeSpace + " bytes");
 
     System.out.println(" === mega bytes ===");
     System.out.println("Total size : " + totalSpace /1024 /1024 + " mb");
     System.out.println("Space free : " + usableSpace /1024 /1024 + " mb");
     System.out.println("Space free : " + freeSpace /1024 /1024 + " mb");
    }
}

Output:

=== Partition Detail ===
 === bytes ===
Total size : 107269320704 bytes
Space free : 50940715008 bytes
Space free : 50940715008 bytes
 === mega bytes ===
Total size : 102299 mb
Space free : 48580 mb
Space free : 48580 mb

How To Loop ArrayList In Java



Four ways to loop ArrayList in Java:
For loop
For loop (Advance)
While loop
Iterator loop

package com.sanjeetpandey.core;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
public class ArrayListLoopingExample {
 public static void main(String[] args) {
 
  List<String> list = new ArrayList<String>();
  list.add("Text 1");
  list.add("Text 2");
  list.add("Text 3");
 
  System.out.println("#1 normal for loop");
  for (int i = 0; i < list.size(); i++) {
   System.out.println(list.get(i));
  }
 
  System.out.println("#2 advance for loop");
  for (String temp : list) {
   System.out.println(temp);
  }
 
  System.out.println("#3 while loop");
  int j = 0;
  while (list.size() > j) {
   System.out.println(list.get(j));
   j++;
  }
 
  System.out.println("#4 iterator");
  Iterator<String> iterator = list.iterator();
  while (iterator.hasNext()) {
   System.out.println(iterator.next());
  }
 }
}

Output:

#1 normal for loop
Text 1
Text 2
Text 3
#2 advance for loop
Text 1
Text 2
Text 3
#3 while loop
Text 1
Text 2
Text 3
#4 iterator
Text 1
Text 2
Text 3

Monday 2 July 2012

Types of java.lang.OutOfMemoryError


java.lang.OutOfMemoryError: Perm Space 
java.lang.OutOfMemoryError: Java heap space 
java.lang.OutOfMemoryError: unable to create new native thread 
java.lang.OutOfMemoryError: requested xxxx bytes for Chunk::new. Out of swap space 


java.lang.OutOfMemoryError: Perm Space 
This indicates JVM ran out of PermSpace.
permspace is specific to jvm implementations. 
For Eg, SUN JVM has one but Jrockit doesn't have an allocated permspace, i.e its part of heap. 
To understand what information is stored in permspace, an example would be: 
classA obj = new classA() 
obj is an object i.e instance of classA. 


Now JVM maintains the structure for "obj" on heap where as stucture for classA will be on permspace. 
This is the reason applications that has lots of classes(libraries, JSPs) tend to occupy more permspace. 
Also, we would see this space used when classloading (dynamic) is done. 
Typical example would be application deployments on appservers like weblogic. 
There is other kinds of information stored on permspace like information for JVM optimizations etc. 


java.lang.OutOfMemoryError: Java heap space 
This is a typical java out of memory from application. 
This message simply says, for this particular request the response from JVM was "OutOfMemoryError". 
Typically we see this message if JVM heap is full and FullGC is not able to reclaim any objects. 
This can be an expected memory shortage or a memory leak. 
Typically out of memory from memory leaks occur over a period of time, where as out of memory from load would occur under peak usage and JVM would recover (continue servicing requests even if some request fails with OutOfMemory error. 
Obviously for load based OOM, increasing heap would help. 
For memory leak scenario, we would have to use profiler tools to get to root cause. JDK6 provides a utility jmap that would serve the basic needs. We can have JVM generate a heap dump on OOM error. The heap dumps can be read by tools like jhat. 
There are lot of commercial tools available like YourKit, Jprofiler etc to analyze memory leaks. 


java.lang.OutOfMemoryError: unable to create new native thread 
This would mean, the java process size has reached its limit. 
When an application creates a java thread object, correspondingly an OS thread has to be created and to create this thread OS tries to reserve space for its stack (thread stack to store local variables) within the process address space. 
In most cases, we will see this error if the application spawns too many threads. 


java.lang.OutOfMemoryError: requested xxx bytes for Chunk::new. Out of swap space 
This would mean the process could not allocate memory as the virtual memory was full. This can happen if there are too many process running on the machine or there is some other process colocated on same machine that consuming most of the process memory. 
If neither is the case, the the current process might be having a native memory leak. This can some from native code within the application and rarely can be from JVM itself which has JNI code.