Thursday, 6 September 2018

Mockito : Mock a method level local object




The method to be tested, which internally creates a local Object of MyOtherClass, which can not be set/mocked via Constructor

public class MyClass {
    public someReturn myMethod(){
        MyOtherClass otherClassObject = new MyOtherClass();
        boolean retBool = otherClassObject.otherClassMethod();
        if(retBool){
            // do something
        }
    }
}


So use power Mock, to say, whenever a new object with default contructor is called, use above object,
and you can add any other propery for your mocked object


@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)  //tells powerMock we will modify MyClass to intercept calls to new somewhere inside it
public class MyClassTest{
    @Test
    public void test(){
          MyOtherClass myMockOtherClass = createMock(MyOtherClass.class);
          //this will intercept calls to "new MyOtherClass()" in MyClass
          whenNew( MyOtherClass.class).withNoArguments().thenReturn( myMockOtherClass ) );          when(myMockOtherClass.otherClassMethod()).thenReturn(true);



   }
Ref : https://stackoverflow.com/questions/29398283/mocking-a-local-object-inside-a-method-of-sut-using-mockito-or-powermocktio?rq=1

Saturday, 25 August 2018

Queue implementation in java


Queue --> Dequeue --> LinkedList

Queue : Only add() from tail and remove() from head (FIFO obviously)







Dequeue: add() and remove() from both the sides methods like addFirst(10),addLast(10),removeFirst(),removeLast().


Notes on LinkedList

1. it maintained all node as 

Node<E> Object attributes{
E item;
Node next;
Node previous;
}

So if you want to implement you own queue/LinkedList,  you should have similars fields

2. remove and add, increase the size field of
Class LinkedList {

int size =0;
Node first/head;
Node last/tail;

}

add(item) {
added to tail, but if head is also null, then head and tail both should point to same.


Sunday, 19 August 2018

Why to override hasCode() and equals() together ?


Lets say your class:

Public Employee {

int empId;

Override only equals()

public boolean equals(Employee other) {

if(this.empId == other.empId) { return true}
else { return false;}

}

You will not face any issues, while using your class , till you start storing your class's object in to any hash implemented collection like HashMap,HashSet etc.


Lets say you want to store you Employee objects in to HashMap.

First lets understand, how HasMap stores the data in it.



Its a Linked List of Linked List
All indexes 0-15 are like linked buckets, then in side each bucket there is another linked list of Map.Entry, for all collision Object with same Bucket Id.


Quick logic of HashMap.put(Key,value)

1.  It first invokes the Key.HashCode() --> say 2001
2. Then tries to find the BucketId/IndexId where it has to place this object --> say divide by n  = 2
3. If next put also result in same bucketId, then that new node will be added to next node of that bucket, line above picture, key4 and key5


Coming back to question again.

Lets your class has only overridden the equals, then each time "new Employee(10)" will produce new Hashcode(Object native memory address , integer representation).

and when you do hashMap.get(new Employee(10), you will never find your object in the map, even though you had added it.

Hence you should provide you unique was of generating hashcode for your class,


Question -2

if you override only HashCode() but not equals

Then suppose your --> new Employee(10) and new Employee(11) goes in to same bucket, then, when you do hasMap.get(new Employee(10)), it will find the bucket, but in the bucket how would find exact object,

becaue inside the bucket each node's "searchedKey.equals(BucketNextkey)" will be invoked, and default implementation of Object's class equal is ==, it check if reference is same,

hence you will never find your Object inside map,even if you has put it.




Monday, 13 August 2018

Threads Creation and Synchronization

Brief

1. A thread can be created either by implementing "Runnable" interface or extending "Thread" class

Inside difference

Thread class internally Implements Runnable interface

and overrides "run" method.

when you call

Thread t = new thread(Runnnable r); --> sets global variable Runnable target = r;

t.start() --> this thread method in Thread class, internally calls local run() and that run method called
target.run().


So if runnable is passed as target, then the class which implements this Runnable.run() will be invoked.

If its thread class is extended , then this target is set as extending class's instance, hence it becames target in run() of thread class.


On Synchronization









Abstract class vs Interface : Use case scenarios


                Abstract class                                                                  Interface 


Most of the properties of these are same, except 

1. Its a class, use "Extends" to inherit it                                         1. Its an interface, use "implements" to inherit it

2. You can have some implement/unimplemented function          2. all functions are bydefault public abstract

3. You can have constructor                                                           3. No constructor allowed


4. Fields/attributes allowed                                                             4. Only constant allowed, Not fields/variable 



Use case scenarios 


                                                                     Interface

1.  To provide some special(HAS-A) capabilities to its all may  be unrelated children, like Employee can be "Serialization"  and Animal can be "Serialization" , after implementing "Serializable" interface both HAS-A property/capability of                 being serialized implementer, 
  
 2. as well as your base has no meaning on it's own
3. You want to define some sort contract/set some fixed behavior/capabilities for all your implementer , walk-able, runnable,flyable etc


                                                                     Abstract

1. IS-A type relation, Dog is Animal, Nano is a Car
2. When you want to reuse the existing code, make inherit properties of you parent and have some of your own.

Thursday, 28 June 2018

Why Static Object and variables never dies


Never dies = Never Garbage collected = Live as long as JVM instance runs

Why never garbage collected ?




Because all Class level details, including all static variable(primitives value and reference values not the actual object actual object will anyway be there in Old/Young gen, only the references ) are
stored in "PermGen" space of Heap.


PermGen :

Holds --> Classloaders objects, which in turn loads classes, hence they hold reference of class they loaded, since statitic variables are references by classes, hence its reference is hold by classloader.

So till the classoader instance itself is destroyed , the static objects lives


When a class loader instance gets GCdown vote
accept
A class in Java can be garbage-collected when nothing references it. In most simple setups this never happens, but there are situations where it can occur.
There are many ways to make a class reachable and thus prevent it from being eligible for GC:
  • objects of that class are still reachable.
  • the Class object representing the class is still reachable
  • the ClassLoader that loaded the class is still reachable
  • other classes loaded by the ClassLoader are still reachable
When none of those are true, then the ClassLoader and all classes it loaded are eligible for GC.

Can permGen data gets garbage collected ? If yes, then Why permGen
TBC




Monday, 5 December 2016

Why Junit doesn't consider other classes as test class

I faced this tricky and very simple problem.
When I created a Maven Java project I got one default test class named "AppTest" and default method "testApp"

With JUnit 3.

Problem:
I created another test class in same package, named "AppTest2" and methods "testApp".
When I run mvn clean test.

It never pick up that class as "Test" class.

Answer :
Junit expect each Test class name to end with "Test", like "AppTest.class","App1Test.class" etc

So I changed the new class name to App1Test.class and it picked all test cases inside during maven build.

Note: I changed the project test cases as JUnit 4-style from JUnit 3-style.
i.e. My test classes no longer extends TestCase 
I annotate each method with @Test, hence my test method name can be anything it need not start with "test"

Monday, 7 November 2016

JAVA Abstraction Vs Encapsulation

ABSTRACTION Vs ENCAPSULATION 


Both are a design and compliments each other.
Abstraction design tells , you should "Show only necessary" menthods to user of your class and Encapsulation tells "Hide All the complexity" of your class.

Abstraction:

Say

Public class Employee {

public void updateSalary() // this one is Public and will be exposed to world

 #Some private property 
 This interns calls 
 getSalary() --> Private
 checkCreditLimits(), // Private
#and other API 

}

Encapsulation

Here  #Some private property will never be visible to user of this class/object


Tuesday, 29 September 2015

ant build: failed saying "can't find symbol" for few classes

Mistake I had made was
1. I had altered my and build.xml,
2. In the build.xml, the test target was before compile :), so since the class file is not yet generated, how can JVM load it.

ant compile issue : warning: [options] bootstrap class path not set in conjunction with 1.6

During the ant build I was facing this issue.

It caused because I had two JDK in my system, 1.6 and 1.7.

I used 1.6 in eclipse as JRE during coding but I was using cmd line for ant build.

In the command line java -version displaying JAVA_HOME as 1.7.

Solution:
Just change the JAVA_HOME via "System environment" in window or equivalent in other OS.

Open New cmd promt.

Sunday, 27 September 2015

JAVA : fibonacci with tail recursive

I recently learnt about tail recursion. I understand, many programming language compilers perform[Current java doesn't] s, code optimization when it finds a recursive method a "Tail recursive".
My understanding of TR : Compiler, does not create new stack frame(instead replace with older call's stack frame) when there is no further operation to be performed after the call has returned

With mycurrent understanding of TR, I think below is a "Tail recursive", because I am not doing any further operation, after the recursive method is returned


suppose totalSeriesLenght = 10.
public void generateFibonacciSeries(int totalSeriesLenght) {
    int firstNum = 0;
    int secondNum = 1;
    printNextFibonacciNumber(firstNum, secondNum,totalSeriesLenght);
}

public void  printNextFibonacciNumber(int fiboOne , int fiboTwo,int totalSeriesLenght) {
    if(totalSeriesLenght >= 1) {
        System.out.print(fiboOne + ",");
        int fiboNext = fiboOne + fiboTwo;           
        totalSeriesLenght --;
        printNextFibonacciNumber(fiboTwo, fiboNext,totalSeriesLenght);
    }
}

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 :)