Monday, 23 February 2015

Find Out Your Java Heap Memory Size and increase it's Size:-

Find Out Your Java Heap Memory Size:-

It's work in the principle of
Ergonomics in the 5.0 Java TM Virtual Machine
how ever it may vary from VM to VM
http://www.oracle.com/technetwork/java/ergo5-140223.html
-------------------------------------------------------------------
1. Java Memory Overview
A quick review of Java memory structure :

1. Java Heap Size
Place to store objects created by your Java application, this is where Garbage Collection takes place, the memory used by your Java application. For a heavy Java process, insufficient Heap size will cause the popular java.lang.OutOfMemoryError: Java heap space.

-Xms<size> - Set initial Java heap size
-Xmx<size> - Set maximum Java heap size

$ java -Xms512m -Xmx1024m JavaApp
2. Perm Gen Size
Place to store your loaded class definition and metadata. If a large code-base project is loaded, the insufficient Perm Gen size will cause the popular Java.Lang.OutOfMemoryError: PermGen.

-XX:PermSize<size> - Set initial PermGen Size.
-XX:MaxPermSize<size> - Set the maximum PermGen Size.

$ java -XX:PermSize=64m -XX:MaxPermSize=128m JavaApp
3. Java Stack Size
Size of a Java thread. If a project has a lot of threads processing, try reduce this stack size to avoid running out of memory.
-Xss = set java thread stack size

$ java -Xss512k JavaApp

Note
The default value for heap size, perm gen, or stack size is differ from different JVMs. The best practice is always defining your own value.
-----------------------------------------------------------------------------------------
C:\>java -XX:+PrintFlagsFinal -version | findstr /i "HeapSize PermSize ThreadSta
ckSize"
   C:\>java -XX:+PrintFlagsFinal -version | findstr /i "HeapSize PermSize ThreadStackSize"

    uintx InitialHeapSize                          := 266634176       {product}
    uintx MaxHeapSize                              := 4267704320      {product}
    uintx PermSize                                  = 21757952        {pd product}
    uintx MaxPermSize                               = 85983232        {pd product}
     intx ThreadStackSize                           = 0               {pd product}
java version "1.7.0_40"
Java(TM) SE Runtime Environment (build 1.7.0_40-b43)
Java HotSpot(TM) 64-Bit Server VM (build 24.0-b56, mixed mode)
Java heap size
InitialHeapSize = 266634176 bytes (256M) and MaxHeapSize = 4266146816 bytes (4068M).
PermGen Size
PermSize = 21757952 bytes (20.75M), MaxPermSize = 85983232 bytes (823. M).
Java Stack Size
ThreadStackSize = 0 kilobytes. (weird…)
The allocated heap memory size is almost same with the ergonomics result :

#ergonomics algorithm
Initial heap size = 16384/64 = 256M
Maximum heap size = 16384/4 = 4096M
------------------------------------------------------
It is possible to increase heap size allocated by the JVM by using command line options Here we have 3 options

-Xms<size>        set initial Java heap size
-Xmx<size>        set maximum Java heap size
-Xss<size>        set java thread stack size

java -Xms16m -Xmx64m ClassName
------------------------------------------------------------------------------------------------------

How many threads can a Java VM support?

--------------------------------
his depends on the CPU you're using, on the OS
and let's done it by a small program:-
public class CountingOfThread {
    private static Object s = new Object();
    private static int count = 0;
    public static void main(String[] argv){
        for(;;){
            new Thread(new Runnable(){
                    public void run(){
                        synchronized(s){
                            count += 1;
                            System.err.println("New thread #"+count);
                        }
                        for(;;){
                            try {
                                Thread.sleep(1000);
                            } catch (Exception e){
                                System.err.println(e);
                            }
                        }
                    }
                }).start();
        }
    }
}
output:-
New thread #4971
New thread #4972
Exception in thread "main" java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(Unknown Source)
at DieLikeADog.main(DieLikeADog.java:20)

How Many Ways We can Create Object in Java:-

There are four different ways to create objects in java:
A. Using new keyword
This is the most common way to create an object in java. Almost 99% of objects are created in this way.
 MyObject object = new MyObject();
B. Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.
MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();
C. Using clone()
The clone() can be used to create a copy of an existing object.
MyObject anotherObject = new MyObject();
MyObject object = anotherObject.clone();
D. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();
Even You can go for this apporach also:-
this.getClass().getClassLoader().loadClass(“com.amar.myobject”).newInstance();
You can read from here

Thursday, 19 February 2015

What does comparison being consistent with equals mean ? What can possibly happen if my class doesn't follow this principle?

The contract of the Comparable interface allows for non-consistent behaviour:
It is strongly recommended (though not required) that natural orderings be consistent with equals.
So in theory, it is possible that a class in the JDK had a compareTo not consistent with equals. One good example is BigDecimal.
Below is a contrived example of a comparator that is not consistent with equals (it basically says that all strings are equal).
Output:
size: 1
content: {a=b}
public static void main(String[] args) {
    Map<String, String> brokenMap = new TreeMap<String, String> (new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            return 0;
        }
    });

    brokenMap.put("a", "a");
    brokenMap.put("b", "b");
    System.out.println("size: " + brokenMap.size());
    System.out.println("content: " + brokenMap);
}

but see now if you store same entry in hashmap
it will store because a.equals(b) always false. so it will store both a and b.
where as in TreeMap it wont thats the problem. because compare b/w a and b is 0...so
 1 will broke single value will store

Difference between Java Comparator and Comparable interfaces

This post explains the difference between most important java interfaces used for sorting namely Comparator and Comparable.
http://www.javacodegeeks.com/2013/03/difference-between-comparator-and-comparable-in-java.html
http://www.programcreek.com/2011/12/examples-to-demonstrate-comparable-vs-comparator-in-java/
ComparableComparator
Class whose objects which we need to sort must implement java.lang.Comparable interface compareTo(Object o1) method
E.g.
If we want to sort Employee, our employee class needs to implement above method.
Class whose objects which we need to sort do not need to implement any interface method.
E.g. 
If we want to sort Employee objects using employee name, We write a class EmpSortByName which implements java.lang.Comparable interfacecompare(Object o1,Object o2) method
Sorting logic is in the same class whose objects are being sorted. Hence this is called Natural ordering of objects.Sorting logic is in separate class. Hence we can write different sorting based on different attributes of objects to be sorted. E.g. Sorting using name, last name, age etc.
We use Collections.sort(List) method to sorting.
E.g
Collections.sort(list);
We must use the Collections.sort(List, Comparator) for sorting.
E.g.
Collections.sort(list, new EmpSortByName());
java.lang.Comparable: int compareTo(Object o1)
This method compares this object with o1 object. Returned int value has the following meanings.
1. positive – this object is greater than o1
2. zero – this object equals to o1
3. negative – this object is less than o1
java.lang.Comparator: int compare(Object o1, Objecto2)
This method compares o1 and o2 objects. Returned int value has the following meanings.
1. positive – o1 is greater than o2
2. zero – o1 equals to o2
3. negative – o1 is less than o1
-----------------------------------------------------------------------------------------------------------------------\
EX:-
public class ComparatorDemo {

    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
                new Person("Joe", 24),
                new Person("Pete", 18),
                new Person("Chris", 21)
        );
        Collections.sort(people, new LexicographicComparator());
        System.out.println(people);
        Collections.sort(people, new AgeComparator());
        System.out.println(people);
    }
}

class LexicographicComparator implements Comparator<Person> {
    @Override
    public int compare(Person a, Person b) {
        return a.name.compareToIgnoreCase(b.name);
    }
}

class AgeComparator implements Comparator<Person> {
    @Override
    public int compare(Person a, Person b) {
        return a.age < b.age ? -1 : a.age == b.age ? 0 : 1;
    }
}

class Person {

    String name;
    int age;

    Person(String n, int a) {
        name = n;
        age = a;
    }

    @Override
    public String toString() {
        return String.format("{name=%s, age=%d}", name, age);
    }
}

Immutable Class Example in Java

public final class ImmtableClass {

    private final String name;
    private final String mobile;

    public ImmtableClass(String name, String mobile) {
        this.name = name;
        this.mobile = mobile;
    }
  
    public String getName(){
        return name;
    }
  
    public String getMobile(){
        return mobile;
    }
}

This Java class is immutable, because its state can not be changed once created. You can see that all of it’s fields are final. This is one of the most simple way of creating immutable class in Java, where all fields of class also remains immutable like String in above case. Some time you may need to write immutable class which includes mutable classes likejava.util.Date, despite storing Date into final field it can be modified internally, if internal date is returned to the client. In order to preserve immutability in such cases, its advised to return copy of original object, which is also one of the Java best practice. here is another example of making a class immutable in Java, which includes mutable member variable.

--------------------------------------------------------------------------

Benefits of Immutable Classes in Java

As I said earlier Immutable classes offers several benefits, here are few to mention:

1) Immutable objects are by default thread safe, can be shared without synchronization in concurrent environment.
2) Immutable object simplifies development, because its easier to share between multiple threads without external synchronization.

3) Immutable object boost performance of Java application by reducing synchronization in code.

4) Another important benefit of Immutable objects is reusability, you can cache Immutable object and reuse them, much like String literals and Integers.  You can use static factory methods to provide methods like valueOf(), which can return an existing Immutable object from cache, instead of creating a new one.

Apart from above advantages, immutable object has disadvantage of creating garbage as well. Since immutable object can not be reused and they are just a use and throw. String being a prime example, which can create lot of garbage and can potentially slow down application due to heavy garbage collection, but again that's extreme case and if used properly Immutable object adds lot of value.

That's all on how to write immutable class in Java. we have seen rules of writing immutable classes, benefits offered by immutable objects and how we can create immutable class in Java which involves mutable fields. Don’t forget to read more about concurrency benefit offered by Immutable object in one of the best Java book recommended to Java programmers, Concurrency Practice in Java.


Reference:---

Read more: http://javarevisited.blogspot.com/2013/03/how-to-create-immutable-class-object-java-example-tutorial.html#ixzz3SCrNlzyn

--------------------------------------------

5 ways to Reverse a String in Java with Example


Monday, 16 February 2015

MultiThreading Example:-Using single application for more


package com.bsl.model;
class TestMultiNaming1 extends Thread{
    static int a, b, c;
 public void run(){
   
     if(Thread.currentThread().getName().equalsIgnoreCase("addition"))
     {
        a= m1();
     System.out.println("addition done"+a+"reading of file done here");
       
         }
     if(Thread.currentThread().getName().equalsIgnoreCase("multiply"))
     {
        b= m2();
             System.out.println("multiply done"+b+"file has been pasted to someother location");
         }
     if(Thread.currentThread().getName().equalsIgnoreCase("equal"))
     {
             c=a+b;  System.out.println("total done"+c);      
         }
 }
 int m1(){
     System.out.println("addition");
    return 9;}
    int m2(){
        System.out.println("multiply");
       return 4;}
    int tt(){
        System.out.println("total");
       return 9;}
public static void main(String args[]){
 TestMultiNaming1 t1=new TestMultiNaming1();
 TestMultiNaming1 t2=new TestMultiNaming1();
 TestMultiNaming1 t3=new TestMultiNaming1();
 t1.setName("addition");
 t2.setName("Multiply");
 t3.setName("equal");
 t1.start();

 try{
  t1.join();
     t2.start();
     t2.join();
   
 }catch(Exception e){System.out.println(e);}
 t3.start();
 }
}  

Sunday, 15 February 2015

Best Of Collection Question In Java.


Differences between HashSet and HashMap in Java
HashSet internally uses HashMap to store objects.when add(String) method called it calls HahsMap put(key,value) method where key=String object & value=new Object(Dummy).so it maintain no duplicates because keys are nothing but Value Object.
the Objects which are stored as key in Hashset/HashMap should override hashcode & equals contract.
Keys which are used to access/store value objects in HashMap should declared as Final because when it is modified Value object can't be located & returns null.

How HashSet Internally Works in Java:-

http://java67.blogspot.in/2014/01/how-hashset-is-implemented-or-works-internally-java.html

------------------------------------------------------------------------------------------------------------------

How HashMap works in java

http://www.javacodegeeks.com/2014/03/how-hashmap-works-in-java.html
 or
http://javahungry.blogspot.com/2013/08/hashing-how-hash-map-works-in-java-or.html?_sm_au_=iVVq5Q1F10JH7NHN

http://javapapers.com/core-java/java-hashtable/
------------------------------------------------------------------------------------------------------------------

http://www.java2blog.com/2014/02/how-hashmap-works-in-java.html

http://javarevisited.blogspot.in/2011/02/how-hashmap-works-in-java.html

Watching vedio must help you:-
https://www.youtube.com/watch?v=iinE6ZBNBjw
------------------------------------------------------------------------------------------------------------------

HashMap – Single Key and Multiple Values Example


http://java.dzone.com/articles/hashmap-%E2%80%93-single-key-and
-----------------------------------------------------------------------------------------------------------------

How to add duplicate key in map:-

http://stackoverflow.com/questions/18922165/how-to-include-duplicate-keys-in-hashmap

if you want to do manually we can use this trick

 if ( ! map.containsKey( key ) ) {
            List list = new ArrayList( );
            list.add( value);
            map.put( key, list);
        }
        else {
            List list = (List) map.get(key);
            list.add( value );
        }

Or if you want to have a single list.add():
        if ( ! map.containsKey( key ) ) {
            List list = new ArrayList( );
            map.put( key, list);
        }
        
        List list = (List) map.get(key);
        list.add( value );
---------------------------------------------------------------------------------------

0r

http://java.dzone.com/articles/allowing-duplicate-keys-java

---------------------------------------------------------------------------------------------------

Why Use Inner Classes?

There are several compelling reasons for using nested classes, among them:
  • It is a way of logically grouping classes that are only used in one place.
  • It increases encapsulation.
  • Nested classes can lead to more readable and maintainable code.
  • ---------------------------------------------------------------------
  • -One good usage of inner classes that comes into my mind is in java.util.ArrayList that hides its iterators implementations into private inner classes. You can't create them except by invoking iterator() or listIterator() on the list object.
    This way the Iterator and ListIterator implementations for ArrayList are grouped with their related class and methods for enhanced readability (the implementations are pretty short), but hidden from others.
----------------------------------------------------------------------------------------------------------------
Best of hash Code by Eclipse
http://eclipsesource.com/blogs/2012/09/04/the-3-things-you-should-know-about-hashcode/

-------------------------------------------------------------------------------------------------------------
ArrayList vs Linked List(when to use linked list)
http://beginnersbook.com/2013/12/difference-between-arraylist-and-linkedlist-in-java/
--------------------------------------------------------------------------------------------------------------