Friday, 30 October 2015

How to find memory leak in java

Tool Name  : - JProfiler,JProb

https://www.youtube.com/watch?v=Dy7WZv5bEV4
https://www.youtube.com/watch?v=DsJgiRp-yLw

What is Java Heap Dump and How to find it in java

C:\Users>jps -l -m
8768 org.jboss.Main
9972 thread.Deadlock
1204 sun.tools.jps.Jps -l -m
10212 sun.tools.jconsole.JConsole 9972
1224

C:\Users>jps -l -m
8768 org.jboss.Main
9972 thread.Deadlock
3520 sun.tools.jps.Jps -l -m
10212 sun.tools.jconsole.JConsole 9972
1224

C:\Users>jmap  -dump:file=GarbageCollection.map 9972
Dumping heap to C:\Users\Synergetic\GarbageCollection.map ...
Heap dump file created

"jhat" - Java heap analysis tool or heap dump file browser: Parses a Java heap dump file and launches a Web server. "jhat" enables you to browse heap dump files using your favorite webbrowser. 

C:\Users>jhat GarbageCollection.map
Reading from GarbageCollection.map...
Dump file created Fri Oct 30 14:27:58 PDT 2015
Snapshot read, resolving...
Resolving 74774 objects...
Chasing references, expect 14 dots..............
Eliminating duplicate references..............
Snapshot resolved.
Started HTTP server on port 7000
Server is ready.



How to find deadlock in Java Application?

C:\>jps -l -m
8768 org.jboss.Main
10164 sun.tools.jps.Jps -l -m
8752 sun.tools.jconsole.JConsole
784
8852 thread.Deadlock

C:\>jstack 8852
2015-10-30 14:03:15
Full thread dump Java HotSpot(TM) Client VM (24.45-b08 mixed mode, sharing):

"DestroyJavaVM" prio=6 tid=0x00dbc000 nid=0x24fc waiting on condition [0x0000000
0]
   java.lang.Thread.State: RUNNABLE

"Thread-1" prio=6 tid=0x00d67c00 nid=0x52c waiting for monitor entry [0x048ff000
]
   java.lang.Thread.State: BLOCKED (on object monitor)
        at thread.YourThread.run(Deadlock.java:79)
        - waiting to lock <0x247330f0> (a java.lang.String)
        - locked <0x24733128> (a java.lang.String)

"Thread-0" prio=6 tid=0x00d67800 nid=0x7ec waiting for monitor entry [0x0486f000
]
   java.lang.Thread.State: BLOCKED (on object monitor)
        at thread.MyThread.run(Deadlock.java:44)
        - waiting to lock <0x24733128> (a java.lang.String)
        - locked <0x247330f0> (a java.lang.String)

"Service Thread" daemon prio=6 tid=0x00d42400 nid=0x2238 runnable [0x00000000]
   java.lang.Thread.State: RUNNABLE

"C1 CompilerThread0" daemon prio=10 tid=0x00d36000 nid=0x20cc waiting on conditi
on [0x00000000]
   java.lang.Thread.State: RUNNABLE

"Attach Listener" daemon prio=10 tid=0x00d35000 nid=0x2408 waiting on condition
[0x00000000]
   java.lang.Thread.State: RUNNABLE

"Signal Dispatcher" daemon prio=10 tid=0x00d33800 nid=0x1fc8 runnable [0x0000000
0]
   java.lang.Thread.State: RUNNABLE

"Finalizer" daemon prio=8 tid=0x00cc0400 nid=0x2544 in Object.wait() [0x0450f000
]
   java.lang.Thread.State: WAITING (on object monitor)
        at java.lang.Object.wait(Native Method)
        - waiting on <0x246f0fb8> (a java.lang.ref.ReferenceQueue$Lock)
        at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:135)
        - locked <0x246f0fb8> (a java.lang.ref.ReferenceQueue$Lock)
        at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:151)
        at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:189)

"Reference Handler" daemon prio=10 tid=0x00cbec00 nid=0x24b4 in Object.wait() [0
x0447f000]
   java.lang.Thread.State: WAITING (on object monitor)
        at java.lang.Object.wait(Native Method)
        - waiting on <0x246f0da0> (a java.lang.ref.Reference$Lock)
        at java.lang.Object.wait(Object.java:503)
        at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:133)
        - locked <0x246f0da0> (a java.lang.ref.Reference$Lock)

"VM Thread" prio=10 tid=0x00cbd800 nid=0x1b44 runnable

"VM Periodic Task Thread" prio=10 tid=0x00d4e800 nid=0x1f20 waiting on condition


JNI global references: 111


Found one Java-level deadlock:
=============================
"Thread-1":
  waiting to lock monitor 0x00d713d4 (object 0x247330f0, a java.lang.String),
  which is held by "Thread-0"
"Thread-0":
  waiting to lock monitor 0x00cc8c0c (object 0x24733128, a java.lang.String),
  which is held by "Thread-1"

Java stack information for the threads listed above:
===================================================
"Thread-1":
        at thread.YourThread.run(Deadlock.java:79)
        - waiting to lock <0x247330f0> (a java.lang.String)
        - locked <0x24733128> (a java.lang.String)
"Thread-0":
        at thread.MyThread.run(Deadlock.java:44)
        - waiting to lock <0x24733128> (a java.lang.String)
        - locked <0x247330f0> (a java.lang.String)


Found 1 deadlock.

Thursday, 29 October 2015

Java Performance Tuning

  9 tools to help you with Java Performance Tuning
  https://blog.idrsolutions.com/2014/06/java-performance-tuning-tools/


10 Application Performance Tuning Tipshttps://blog.codecentric.de/en/2012/07/10-application-performance-tuning-tips/

The Principles of Java Application Performance Tuning

http://www.cubrid.org/blog/dev-platform/the-principles-of-java-application-performance-tuning/

Thursday, 8 October 2015

Single Design Pattern with Double locked checking...........

import java.io.Serializable;

public class LazyBizService implements Serializable {

private volatile static LazyBizService bizService;

private LazyBizService() {
System.out.println("____BizService is instantiated___");
}

static public LazyBizService getInstance() {
if(bizService==null) {
   //synchronized block
   synchronized (LazyBizService.class) {
    if(bizService==null) {
      bizService=new LazyBizService();
    }  
}
}
  return bizService;
}

// This will fix the de-serialization issue
    private Object readResolve() {
         // Return the available instance instead.
         return bizService;         
    }
}

How to find JDK version and bit (32/64)

java -d32  -version
java version "1.7.0_45"
Java(TM) SE Runtime Environment (build 1.7.0_45-b18)
Java HotSpot(TM) Client VM (build 24.45-b08, mixed mode, sharing)


java -d64  -version
Error: This Java instance does not support a 64-bit JVM.
Please install the desired version.

Why ArrayList is used when we fetch data from database and render it on the GUI?


JVM Block Diagram! and Java Class Loader


Java Class Loader


Java ClassLoader loads a java class file into java virtual machine. It is as simple as that. It is not a huge complicated concept to learn and every java developer must know about the java class loaders and how it works.

Types (Hierarchy) of Java Class Loaders

Java class loaders can be broadly classified into below categories:
  • Bootstrap Class Loader
    Bootstrap class loader loads java’s core classes like java.lang, java.util etc. These are classes that are part of java runtime environment. Bootstrap class loader is native implementation and so they may differ across different JVMs.
  • Extensions Class Loader
    JAVA_HOME/jre/lib/ext contains jar packages that are extensions of standard core java classes. Extensions class loader loads classes from this ext folder. Using the system environment propery java.ext.dirs you can add ‘ext’ folders and jar files to be loaded using extensions class loader.
  • System Class Loader
    Java classes that are available in the java classpath are loaded using System class loader.


What is a StackOverflowError and Java Stack.................

Parameters and local variables are allocated on the stack (with reference types the object 
lives on the heap and a variable references that object). The stack typically lives at the upper end of your address space and as it is used up it heads towards the bottom of the address space (i.e. towards zero).
Your process also has a heap, which lives at the bottom end of your process. As you allocate memory this heap can grow towards the upper end of your address space. As you can see, there is the potential for the heap to "collide" with the stack (a bit like tectonic plates!!!).
The common cause for a stack overflow is a bad recursive call. Typically this is caused when 
your recursive functions doesn't have the correct termination condition, so it ends up calling itself forever. However, with GUI programming it's possible to generate indirect recursion. For example, your app may be handling paint messages and whilst processing them it may call a function that causes the system to send another paint message. Here you've not explicitly called yourself, but the OS/VM has done it for you.
Example of Stack in Java Thread Object
enter image description here

Define the size of Java statck of thread object in JVM


Define the size of Java Heap for JVM

java   -Xms128M  -Xmx256M    Magic

Note : Do not write .class 

-Xms128M -> Initial Size for Java Heap
-Xmx256M -> Max Size for Java Heap


























Interface is contract between two module/program so that they can communicate to each other....
Example : Servlet is interface  and using this interface Servlet Container and our servlet 
(which we define by extending HttpServlet) are communicate to each other.

Interface is contract to expose the functionality to the user and it also hides detail implementation from the user....

Other words using interface, user can access the functionality without knowing implementation and User code will not change if implementation changes..... 

Examples:
jdbc programming......
RMI
EJB
abstract means you cannot see implementation......


Note :Generally first of all interface comes in the picture...
We have interface in out project to implement dao layer,service ,Facade Layer etc....


Example:-
Questions :

Where have you used generics in your project?
or 
Where have you used Interface and Abstract class in your project?

Common Contract for DAO Layer

public abstract interface AbstractDao<E, I extends Serializable> {

    public E findById(I id);
    public void saveOrUpdate(E e);
    public List<E> findByCriteria(Criterion criterion);
    public List<E> findAll();
    public void delete(E e);
    public List<E> findByAttributeAndValue(I attribute,I value);
    public List<E> getEntityListForRowNumbers(int initialRowNumber,int maximumRowNumbers);
    public int getCount();
    public List<E> findTopNRandomRows(int count);
    List<E> findTopNRandomRowsWithAttributeAndValue(int numRows, I attribute, I value);

}

Define the Abstract class to implement common behavior for all the entities..


AbstractDaoImpl.java

/**
 * @author yadna01
 * @param <E>
 * @param <I>
 */
public abstract class AbstractDaoImpl<E, I extends Serializable> implements
AbstractDao<E, I> {

private Class<E> entityClass;

protected AbstractDaoImpl(Class<E> entityClass) {
this.entityClass = entityClass;
}

@Autowired
@Qualifier("synegySessionFactory")
private SessionFactory psessionFactory;


public Session getCurrentSession() {
return psessionFactory.getCurrentSession();
}

@SuppressWarnings("unchecked")
@Override
public E findById(I id) {
return (E) getCurrentSession().get(entityClass, id);
}

@Override
public void saveOrUpdate(E e) {
/*System.out.println("Object to save" + e);*/
getCurrentSession().saveOrUpdate(e);
}

@Override
public List<E> findTopNRandomRows(int count) {
Criteria criteria = getCurrentSession().createCriteria(entityClass);
criteria.add(Restrictions.sqlRestriction("1=1 order by rand()"));
criteria.setMaxResults(count);
return criteria.list();
}

@Override
public void delete(E e) {
getCurrentSession().delete(e);
}

@SuppressWarnings("unchecked")
@Override
public List<E> findByCriteria(Criterion criterion) {
Criteria criteria = getCurrentSession().createCriteria(entityClass);
criteria.add(criterion);
return criteria.list();
}

public Criteria findByCriteria() {
Criteria criteria = getCurrentSession().createCriteria(entityClass);
return criteria;
}

@SuppressWarnings("unchecked")
@Override
public List<E> findAll() {
return getCurrentSession().createQuery("from " + entityClass.getName())
.list();
}

@Override
public int getCount() {
Number rowCount = (Number) getCurrentSession()
.createCriteria(entityClass.getName())
.setProjection(Projections.rowCount()).uniqueResult();
return rowCount.intValue();
}

public List<E> getEntityListForRowNumbers(int initialRowNumber,int maximumRowNumbers){
   Criteria criteria = this.getCurrentSession().createCriteria(entityClass);
//criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
criteria.setFirstResult(initialRowNumber);
criteria.setMaxResults(maximumRowNumbers);
List<E> list = (List<E>) criteria.list();
return list;
}

@Override
public List<E> findByAttributeAndValue(I attribute, I value) {
@SuppressWarnings("unchecked")
List<E> list = getCurrentSession().createQuery(
"from " + entityClass.getName() + " e where e." + attribute
+ " like '" + value + "'").list();
return list;
}

@Override
public List<E> findTopNRandomRowsWithAttributeAndValue(int numRows, I attribute, I value) {
Criteria criteria = getCurrentSession().createCriteria(entityClass);
criteria.add(Restrictions.eq(attribute.toString(), value));
criteria.add(Restrictions.sqlRestriction("1=1 order by rand()"));
//criteria.add(Restrictions.sqlRestriction(attributeName + "=" + value + " order by rand()"));
criteria.setMaxResults(numRows);
List<E> output = criteria.list();
System.out.println("Number of results is " + output.size());
for(E e : output) {
System.out.println(e.toString());
}
return output;
}

}


@Repository("BankCustomerLoginHibernateDaoImpl")
@Transactional(propagation=Propagation.REQUIRED,value="transactionManager")
public class BankCustomerLoginHibernateDaoImpl extends AbstractDaoImpl<CustomerLoginDetailEntity,String> {
 
protected BankCustomerLoginHibernateDaoImpl() {
        super(CustomerLoginDetailEntity.class);
    }

//@Transactional(propagation=Propagation.REQUIRED) == annotation will not work 
//for super class method since it is applied 
public void save(CustomerLoginDetailEntity customerLoginDetailEntity){
super.saveOrUpdate(customerLoginDetailEntity);
}


@SuppressWarnings("unchecked")
public CustomerLoginDetailEntity findById(String id) {
CustomerLoginDetailEntity customerEntity=super.findById(id);
return customerEntity;
}


}