Showing posts with label Core java. Show all posts
Showing posts with label Core java. Show all posts

Saturday 18 April 2015

Getting JVM heap size, used memory, total memory using Java Runtime

Getting JVM heap size, used memory, total memory using Java Runtime.

Reading runtime java virtual memory usage is useful when the system/application is struggling in getting resources. System Memory is one of the main resource that an application developer has to consider while managing the application.

Java’s Runtime class provide lot of information about the resource details of Java Virtual Machine or JVM. The memory consumed by the JVM can be read by different methods in Runtime class. Following is the  example of reading JVM Heap Size, Total Memory and used memory using Java Runtime api.

 public class MemoryUtilization {  
   public static void main(String [] args) {  
     int conversion = 1024*1024;       
     Runtime runtime = Runtime.getRuntime();       
     System.out.println("##### Heap utilization #####");       
     System.out.println("Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / conversion);  
     System.out.println("Free Memory:" + runtime.freeMemory() / conversion);  
     System.out.println("Total Memory:" + runtime.totalMemory() / conversion);       
     System.out.println("Max Memory:" + runtime.maxMemory() /conversion);  
   }  
 }  

Thursday 16 April 2015

How to create a read-only collection in java?

Collections is one of the most used feature in Java/J2EE applications . Read only List means a List where you can not perform modification operations like add, remove or set. You can only read from the List by using get method or by using Iterator of List, This kind of List is good for certain requirement where parameters are final and can not be changed. In Java you can use Collections.unModifiableList() method  to create read only List , Collections.unmodifiableSet() for creating read-only Set like read only HashSet and similarly creating a read only Map in Java.



 import java.util.ArrayList;  
 import java.util.Collections;  
 import java.util.List;  
 public class ReadOnlyCollections {  
           public static void main(String[] args) {  
                List<String> myList = new ArrayList<>();  
                myList.add("1");  
                myList.add("2");  
                myList.add("3");  
                System.out.println(myList);  
                // Convert to unmodifiable .  
                myList = Collections.unmodifiableList(myList);  
                myList.add("4");  
                System.out.println(myList);  
           }  
 }  
 Output -   
 [1, 2, 3]  
 Exception in thread "main" java.lang.UnsupportedOperationException  
      at java.util.Collections$UnmodifiableCollection.add(Unknown Source)  
      at ReadOnlyCollections.main(ReadOnlyCollections.java:15)