Wednesday, 27 May 2015

Will static Object be garbage collected ?

Static Objects are per JVM/Classloader ?

Their reference resides in PermGen but actual object will be created in the Old/Young generation of heap.

Will that ever cause OOM:Heap space of OOM: Permgen space ?

If you are holding static reference to a growable Object collection, you should get OOM:Heap space not OOM: PermGen

GC'ed :
Never, till the classloader which loaded the class, itself gets GC'ed.
That never happens for default classloader

Will String literals be garbage collected ?

EDIT: Below is for till JAVA6, in JAVA 7 String literal pool has been moved from PermGen to Normal Heap,

Adv : PermGen Size is fixed and less, where Normal HEAP size is increasable and large

Still LITERAL pool is in separate space of Heap.



-----



Why
Java Says Only one copy of String, every one get's the reference of the same.

NOte: When you create same string  value "Bangalore" via New String, jvm creates new object in Heap but internally, that new object will also point to same String available in String literal pool

String first = "bangalore"
String second = "bangalore"

first==second // Troe, Just referenc check, both points to same object in SLT/SCP

String firstStr = new String("bangalore");
String secondStr = new String("bangalore");

firstStr ==secondStr //False, both have new address reference in HEAP, although, both heap may point to same string in SLP/SCP

firstStr.squals(secondStr) // TRUE,Since String overrides the equal meth of java.lang.Object and checks char by char of equality,default implementation in Object class just check for reference equality. Obj1==Obj2


WHY STRING WAS MADE SPECIAL:
1. To improve performance, if same string is created again, java just return the reference from SLP .
2. Issue with this approach was , if all thread points to same String and thread1 makes modification, all other threads will have a new undesirable value.

3. to overcome that, they made String objects immutable(Final, so one extends and change the behavior, fields were private(If public then fields value can be changed with object reference, so setter method, all the alteration functions creates new string object and return the new reference.

Also if String is your key in HashMap, if String was not immutable, any change to reference would directly change the Key in hashmap, and receivers of hashMap, would not be able to search your entry with already agreed key.



Stored where

It's added in to Array of String called "String constant pool" , placed inside "PERMGEN" SECTION OF HEAP

Never garbage collected


Who has the reference ?

All the codes which created it, and codes information will be available in the CLASS which is loaded by a classloader, and default classloader never gets GC'ed.

Hence those string will live there forever.

Now does Actual String Object resides in Old/Young generation and Constant pool array, holds only references to it ?

I need to find out.

Sunday, 17 May 2015

Thread Synchronization strategy


Requirement

Two thread wants to make sure they don't run if other thread is running.

Simple approch

1. Both work on single object
2. Wait on the object property, like "isAvailable"
3. call notify once they complete the task.

But what if the thread never reset the condition ?


Approch second

1. Ask every one to pass "Task" object
2. call task object runTask()
3. every thread have some inner class of seperate myTask implements Task interface and overrides runTask()
4. Put the main task, which requires exclusive lock, inside this method.

Issue:
Forces every one to follow this framework, implement interface etc

How Blocked thread and Wait thread wakes up ?


Scenario.

Thread A goes in side a Synchronized method hence acquires the Lock of that OBJECT.
While the Thread A is inside Syc Block, Two more Threads (Thread B and C) tries to execute that Sync block, Since lock is acquired from Thread A, subsequent Thread B and C are in BLOCKED state.

Now Assume, some condition inside the Sync Block has not meet and then Thread A goes to Wait state, and thus relinquishing the LOCK of Object.

ex :

    public synchronized void getLock()  {
            while (!isLockAvailable) {
                wait();
             //Do some task
             sleep(10000);
             isLockAvailable=true
            }
           
            //Set the flag so that next thread waits in the while loop
            isLockAvailable = false;

    }

Now .....
TO be completed 

What happens If Singleton object is not STATIC ?

Look at the below code 

   private static AnalyticsLogRotator intance = null;

    public static synchronized AnalyticsLogRotator geInstance() {
        if(intance == null) {
            intance = new AnalyticsLogRotator();
        }
        return intance;
    }


If instance, is not STATIC, you will not be able to refer it from static method geInstance().
If getIstance() is not static method, you will not be able to invoke it without creating an object of this class.
And if can create an object of this class on your own, then it will not be singleton :)