Posts

Showing posts from May, 2010

Understanding Java Garbage Collector

Image
     Java’s garbage collection system reclaims objects automatically occurring transparently, behind the scenes, without any programmer intervention. It works like this: when no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object is released. This recycled memory can then be used for a subsequent allocation. Although it complete transparent to developer, understanding how GC works helps developer to improve efficiency of Java Program. It is also helpful to improve performance of the program. JDK provides many runtime options to analysis GC and analysis your program behavior. Here is the simple java program to understand GC behavior 1: public class GCTest { 2: public GCTest() { 3: } 4: 5: public static void main(String[] args) { 6: int count = 10000; 7: long startTime = System.currentTimeMillis(); 8: System.out.println(" Total Count = " + count...

Concurrency in Singleton Designing Pattern

      Please refer previous post for Singleton Designing Pattern . Concurrency is the one of the major issues with singleton designing pattern.       There will be multiple client accessing same singleton resource instance. If this resource is mutable then concurrency need to be taken care . Example from previous post is being used here. 1: package demo.singleton; 2: import java.util.concurrent.locks.ReadWriteLock; 3: import java.util.concurrent.locks.ReentrantReadWriteLock; 4: /** 5: * Singleton Resource Class 6: * @author Yogesh 7: */ 8: public class SingletonResource { 9: private static SingletonResource resorce = null ; 10: int count; 11: private ReadWriteLock writeLock = new ReentrantReadWriteLock(); 12: 13: public static SingletonResource getInstance(){ 14: if (resorce == null ){ 15: synchronized (SingletonResource. class ){ 16: if (res...

Singleton Design Pattern by example

Image
Singleton design pattern is most commonly used among all available java design patterns. It is a Creational patterns. Basic purpose of this design pattern is to maintain only one instance of a class throughout the application. This class may represent a common shared resource, functionality etc. When to Use ? You should consider singleton design pattern in following scenario A resource is shared across all application component and only one instance of resource is possible. Global variables are being passed across all part of application Multiple instances representing same kind of information. How to Use ? It is very simple to implement this design pattern. Following are he key requirements and possible solution for implementing singleton design pattern. Only one instance should be available at the time – restrict the class instantiation using private scoped constructor. Everybody should get same instance – maintain a private static instance variable ...