Wednesday, 3 May 2017

Frequntly asked Interview questions related to Multi Threading in Java

                       I believe, Multi Threading is always an interesting topic. Here, it is the list of frequently asked interview questions related to it. 

1.) What is the difference between Process and thread? 
- How thread switching is good than process switching?
- Life cycle of thread.
- Advantages of multi threading.
- What is difference between user Thread and daemon Thread?

2.) How can we create thread in Java? 
- What is the better way? Extending Thread class or to implement Runnable interface?
- How to create Demon thread in Java?

3.) Difference between start() and run()
- What will happen if we don’t override Thread class run() method?
- Can we call run() without start()? What will happen at that time?
- Can we call run() method of a Thread class?

4.) What is Thread.join() ?
- What do you understand about Thread Priority?
- There are three threads T1, T2, and T3? How do you ensure sequence T1, T2, T3 died before main thread in Java?
- How can we make sure main() is the last thread to finish in Java Program?

5.) wait() vs notify() vs notifyAll() 
- Why they are part of Object class but not Thread class?
- Why these methods have to be called from synchronized method or block?
- What is the difference between calling wait() and sleep() method in Java multi-threading?

6.) What is the difference between Thread.sleep() and Thread.yield() ?
- Why Thread sleep() and yield() methods are static?

7.) What is the difference between the intrupt(), interrupted() and isInterrupted() method in Java?

8.)  What is the difference between Runnable and Collable in Java?
- What is FutureTask in Java?

9.) How to stop a thread in java?
- Why stop(), suspend() and resume() were deprecated.?

10.) What happens when an Exception occurs in a thread? 
- What happens if a thread throws an Exception inside synchronized block?

11.) What is race condition? Give an example.
- What is the solution for that?

12.) What is busy spin in multi-threading?

13.) How can we achieve thread safety in Java?
- Which is more preferred – Synchronized method or Synchronized block?

14.) What is ThreadLocal?
- What is Thread Group? Why it’s advised not to use it?

15.) What is Thread Pool? 
- How can we create Thread Pool in Java?
- What is the difference between the submit() and execute() method thread pool in Java? 
- What happens if you submit a task when the queue of the thread pool is already filled?

16.) What is Thread Scheduler and Time Slicing?
- How can we pause the execution of a Thread for specific time?

17.) How does thread communicate with each other?

18.) How do you share data between two thread in Java?

19.) What is volatile keyword in Java?
- What is the difference between the volatile and atomic variable in Java?

20.) What is Java Thread Dump. How can we get Java Thread dump of a Program?
- Which JVM parameter is used to control stack size of a thread?

21.) What is Java Memory model?

22.) How do you check if a Thread holds a lock or not?

23.) What is blocking method in Java?

24.) What is dead lock? 
- What is Live lock?
- How can we detect that its a dead lock? 
- How to break deadlock? 
- What are the situations which we need to take care so that it can not occur? 
- A sample program which creates a deadlock as well as Live lock.

25.) What is Semaphore in Java? 

26.)  What is the difference between CyclicBarrier and CountDownLatch in Java?

27.) What is ReadWriteLock in Java?

28.) What is the difference between synchronized and ReentrantLock in Java?

29.) Write code to solve Producer Consumer problem in Java? 

30.) What is the fork-join framework in Java? 
- What are new things in JDK 7 related to multi threading?

31.) List down 3 multi-threading best practice you follow?
Answers: 
- Always give meaningful name to your thread.
- Avoid locking or Reduce scope of Synchronization
- Prefer Synchronizers over wait and notify
- Prefer Concurrent Collection over Synchronized Collection

Tuesday, 7 June 2016

Garbage Collection in Java

Question: What is responsiveness and throughput parameter for any web application?

Responsiveness
Throughput
Refers to how quickly an application or system responds with a requested piece of data.

Focuses on maximizing the amount of work by an application in a specific period of time.
Long pause times are not acceptable for applications that focus on throughput.

High pause times are acceptable for applications that focus on throughput.

The focus is on responding in short periods of time.
Since high throughput applications focus on benchmarks over longer periods of time, quick response time is not a consideration
E.g. how quickly UI responds, how fast a website returns a page, how fast a database query is returned etc.

The number of transactions/jobs/queries/etc completed in a given time.

Question: Which things are stored in Heap and in stack or diff between Heap Space and Stack Space?

Java Heap space
Java Stack space
It is used by java runtime to allocate memory to objects and JRE classes.
(It is used by all the parts of the application.)

It is used for execution of a thread.
(It is used only by single thread of execution.)

New objects are created in Heap space.
(Stack memory contains the references to it.)

It stores Method specific vales, local primitives and references to other objects in the heap that are getting refereed from the method.

Objects stored in the heap are globally accessible.

Stored values cannot be accessible by other threads.

GC runs on the heap memory to free the memory used by objects that does not have any references.
(Heap memory lives from the start till the end of the application/freed by GC)

In the end of the execution of the method, the unused memory becomes available for next method.
(Stack memory is short-lived)

Heap space is bigger than stack space.
(Heap memory is divided into parts like young generation, old generation and perm gen.)

In comparison with each other, access from Heap memory is slower than Stack memory.

Stack size is very small compared to Heap memory.

Because of the simple design (LIFO) and less size, stack memory is faster than Heap.


When Heap memory is exhausted, java runtime throws java.lang.OtOfMemoryError

When stack memory is full, java runtime throws java.lang.StackOverFlowError

For tuning, we can mainly use following parameters.
–Xms(define the startup sizeof the Heap)
–Xmx(define maximum size of the Heap)

For tuning, we can mainly use following parameters.
- Xss(define the stack memory size)

Question: What is Automatic Garbage Collection? When does an object become eligible for garbage collection?

Unlike other programming languages, process of deallocating memory in Java is not manual. It is handled by Garbage Collector- a system thread. Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects.

An object becomes eligible for GC when there is no live reference for that object or it can not be reached by any live thread. If two objects have cyclic dependency on each other and both have no live reference then also both objects are eligible for GC.

Question: What are Young (New) Generation, Old Generation, Permanent Generation, Eden memory, S0 Survivor memory, S1 Survivor memory, Minor Garbage collection, Major Garbage Collection and “Stop the world” events? Which things are stored in these areas? What is permanent Generation? What are the changes in JDK 1.8? What is Metaspace?

Young Generation: Young generation is the place where all the new objects are created. When young generation is filled completely, garbage collection is performed. This garbage collection is known as Minor GC. Young generation is also known as New Generation. Young Generation is divided into following sections: Eden Memory and two Survivor Memory (S0 Survivor memory and S1 Survivor memory) spaces.

Eden Memory:  Most of the newly created objects are located in the Eden memory space. When it is filled with objects, minor GC is performed and objects are moved to one of the survivor space.

Survivor Memory: Survivor memory has two sections S0 Memory space and S1 Memory space which are also known as From-space and To-space. Each minor GC done in the young generation increments the age of objects in the survivor spaces. When an object has survived a sufficient number of minor GCs (Defaults vary but normally start at 15) it will then be promoted to the Old Generation.

Old Generation: The Old Generation is usually much larger than the New Generation and it contains the objects that are long lived and survived after many rounds of Minor GC. Usually garbage collection is performed in Old Generation memory when it’s full. Old Generation Garbage Collection is called Major GC and usually takes longer time.

Stop the World events: All application threads are stopped during the execution of GC. This event is known as Stop the World event. Minor GC and major GC both are this type of events. Often a major collection is much slower because it involves all live objects.

Permanent generation (PermGen): It contains metadata required by the JVM to describe the classes and methods used in the application. Java SE classes and methods are also stored in it. Runtime, it is populated by JVM, based on classes used in the application. The permanent generation is included in a full garbage collection.

Java 8: PermGen is no longer exists in Java 8. Java designers have redesigned the architecture and they removed PermGen and introduced new area so called Metaspace




Monday, 30 May 2016

Commonly asked differences during Java interview.

Map vs Set vs List

ArrayList vs Vector
HashMap vs HashTable
HashMap vs HashSet

Iterator vs Enumeration
Fail-fast and Fail-safe Iterators
Iterator vs ListIterator
Why ListIterator has added() method but Iterator does not have it?
Comparable and Comparator Interface

Working example of compareTo(), comparable, equals(), hashCode().


Synchronized Collection vs Concurrent collection

ArrayList vs Vector vs CopyOnWriteArrayList
HashMap vs HashTable vs ConcurrentHashMap
Can we replace Hashtable with ConcurrentHashMap?
Queue - BlockingQueue
HashTable vs ConcurrentHashMap (putIfAbsent)
What is lock striping in java? 


poll() vs remove()


Singleton Design Pattern
Iterator Design Pattern.



Commonly asked interview questions:
1.) How Hashmap works in java? 
2.) How Hasmap get() and remove() works in java?
3.) How Hashset works in java?
4.) How does Linkedlist implemented in java? Is it singly linkedlist or doubly linked list?

5.) What is Marker interface or Tag interface? Examples of it(Serializable, Clonnable, RMI and Remote interfaces, RandomAccess...)


6.) Which is better to use? Annotations or Marker interface?
7.) What is Clonnable interface? Why it is use? When it is used? How it is used?
8.) What is Serializable interface? Why it is use? When it is used? How it is used?

9.) What is TreeMap, Naviagable Map and WeakHashMap, IdentityHashMap?

10.) WeakReference vs SoftReference vs PhantomReference vs Strong reference

11.) How can an Arraylist be synchronized without using Vector?

Ans) Arraylist can be synchronized using:
Collections.synchronizedList(List list)
Collections.synchronizedMap(Map map)
Collections.synchronizedCollection(Collection c)

12.)  How do you remove an entry from a Collection? OR 

What is difference between remove() method of Collection and remove() method of Iterator?
Which one you will use, while removing elements during iteration.


Thread:

What is the difference between start and run method in Java Thread? 
( thread.start() vs thread.run() )
How to avoid deadlock?
Write producer-consumer problem?
Solve it by using wait() and notify(). Solve it by using BlockinQueue. Which is better?

What are the other thread scheduler? like quartz, threadpool Executors?





List Set Map
Ordered collection
(It preserves the order on which an element is inserted. )

(Also known as Dynamic Array.)
Unordered collection
(It does not preserve the order.)


(We can have SortedSet which offers to sort functionality e.g: TreeSet.)


(Also we can change/override it by using Comparator and Comparable. )
Key-Value based collection
List allows duplicate values.
It can store multiple times null as value.
Set does not allow duplicate values.
So it can store only one time null as value.
(Duplication of object is detected by using equals() )


(If two objects are equal using equals() then the later object will replace the former object.)


(In case of SortedSet like TreeSet, compareTo() is used to compare object and decide whether an object   is duplicate or not. )


Duplicate keys are not allowed.


It can contain only one null key but can contain duplicate values.






e.g. ArrayList, LinkList, Vector e.g HashSet e.g HashMap, LinkedHashMap,   TreeMap


Sunday, 29 May 2016

Ant and triangle problem

Three ants are sitting at the three corners of an equilateral triangle. 
Each ant starts randomly picks a direction and starts to move along the edge of the triangle. 
What is the probability that none of the ants collide?
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Answer: 0.25 or 25%
Probability of no collision = Probability of all ants go in a clockwise direction + Probability of all goes in an anti-clockwise direction) 
Probability of no collision = (0.5 * 0.5 * 0.5) + (0.5 * 0.5 * 0.5) 
Probability of no collision = 0.25

100 door puzzle

You have 100 doors in a row that are all initially closed. you make 100 passes by the doors starting with the first door every time.
The first time through you visit every door and toggle the door (if the door is closed, you open it, if its open, you close it). The second time you only visit every 2nd door (door #2, #4, #6). The third time, every 3rd door (door #3, #6, #9), etc, until you only visit the 100th door.

Question: what state are the doors in after the last pass? which are open which are closed?
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Answer:
Only perfect square doors will be open at the end.
( If all doors are initially opened then only perfect square doors will be close at the end. )

Two door, which path leads to heaven?

You are standing before two doors. One of the path leads to heaven and the other one leads to hell.

There are two guardians, one by each door.
You know one of them always tells the truth and the other always lies, but you don’t know who is the honest one and who is the liar.

You can only ask one question to one of them in order to find the way to heaven.

What is the question?
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Answer:
"If I ask the other guard about which side leads to heaven, what would he answer?"

Let say path of heaven is 'Left' then...
Answer from the guard who always speaks truth... 'Right'.
Answer from the guard who always lie... 'Right'.

So you can get that hell is on Right side and heaven is in Left.  :D

Note:
If you ask "which side leads to heaven" then
Answer from the guard who always speaks truth... 'Left'.
Answer from the guard who always lie... 'Right'.
:) 

)

Find black/white pair of socks

There are 10 black socks and 10 white socks in a drawer.
Now you have to go out wearing your shoes.
So how many maximum number of times you need to remove the sock from drawer so that you can go out?

You can remove only 1 sock at a time. Obviously, you can’t go outside wearing different socks!
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Answer:
3

Find the celebrity in the party

There are n people in a party, they might or might not know each others names.

There is one celebrity in the group, celebrity does not know any of n-1 peoples by name and all n people know celebrity by name.

You are given the list of people’s names, You can ask only one question from the people. Do you know this name ?

How many maximum number of questions you need to ask to know the celebrity name?

Note: assume all names are unique. and you know the persons by name(but don’t know if he is celebrity)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Answer:
n-1 questions

If we ask a question to a person A about person B that... "Do you know him?"
If person A say yes... then A is not celebrity but B is definitely.
If person A say  no... then A might be a celebrity but B is definitely not a celebrity.

If we are asking this question to everyone in the party, then in worst case when last two persons are remaining then we get our answer.
So (n-1) questions are require to ask.

Two egg puzzle

We are given two eggs, and access to a 100-story building. Both eggs are identical.
The aim is to find out the highest floor from which an egg will not break when dropped out of a window from that floor. If an egg is dropped and does not break, it is undamaged and can be dropped again. However, once an egg is broken, that’s it for that egg.

If an egg breaks when dropped from floor n, then it would also have broken from any floor above that. If an egg survives a fall, then it will survive any fall shorter than that.

The question is:
What strategy should you adopt to minimize the number egg drops it takes to find the solution?.
And what is the worst case for the number of drops it will take?
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Answer:
14

x + (x-1) + (x-2) +...+ 1 = 100
Sigma(x) = 100
x*(x+1) / 2 = 100
x(x+1) = 200
x = 13.65
x = 14

Detailed answer:
http://datagenetics.com/blog/july22012/index.html
http://www.programmerinterview.com/index.php/puzzles/2-eggs-100-floors-puzzle/

25 horse, 5 tracks, find 3 fastest horses

We have 25 horses, and we want to pick the fastest 3 horses out of those 25.
We have only 5 tracks. Means, in each race, only 5 horses can run at the same time.

What is the minimum number of races required to find the 3 fastest horses without using a stopwatch?
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Answer:
7

First 5 race should be held among 25 horses.
6th race should be held among... winner of every race.
7th race should be among...
( Second and Third horses from the group of first winner of 6th race,
  top two horses from the group of  second winner of the 6th race,
  top horse from the  group of third winner of 6th race. )

Measure "4 liter water" problem

We have two buckets, 1 of capacity 3 liter and another of 5 liter. We have 5 liters of water.

So how will we make combinations such that 1 bucket will have exactly 4 liters of water?
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Answer:
Let say Bucket B1 has capacity of 5 Liter and B2 has 3 Liter.)

1.) Full B1 bucket with water. ( B1-5L, B2-0L)
2.) Empty B1 into B2. (B1-2L, B2-3L)
3.) Empty B2 bucket. (B1-2L, B2-0L)
4.) Emty B1 into B2. (B1-0L, B2-2L)
5.) Full B1 bucket. (B1-5L, B2-2L)
6.) Empty B1 into B2. (B1-4L, B2-3L)

Red Blue marble - probability puzzle

We have 50 red marbles, 50 blue marbles and 2 jars. 
One of the jars is chosen at random and then one marble will be chosen from that jar at random. 
How would you maximize the chance of drawing a red marble? What is the probability of doing so? 
All 100 marbles should be placed in the jars.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Answer:
Put a single Red marble in one jar. And rest of 99 in other jar.
Which gives the maximum probability.
= ((1/2)*1)  +  (( 1/2)*(49/99))
= 0.50 + 0.2474
= 0.7474
= 0.75 or 75%

Mislabeled jar - Jelly Beans problem

This problem is also called Jelly Beans problem. This is the most commonly asked interview puzzle.

You have 3 jars that are all mislabeled.
One jar contains Apple, another contains Oranges and the third jar contains a mixture of both Apple and Oranges.
Labels on jars are as follows: Apples, Oranges, Apples+Oranges

You are allowed to pick as many fruits as you want from each jar to fix the labels on the jars.

What is the minimum number of fruits that you have to pick and from which jars to correctly label them?

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Answer:









We 

have 100 coins laying flat on a table, each with a head side and a tail side. 10 of them are heads up and rest of 90 are tails up. 

You can't feel, see or in any other way find out which side is up. 

Split the coins into two piles such that there are the same number of heads in each pile. 
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Answer:
Divide all 100 coins into two piles. (irrespective of pile-size)

And flip all the coins in any one pile.

which gives equal number of heads and tails in both piles.

Crossing the bridge puzzle

Adam, Bob, Clair and Dave are out walking:

They come to rickety old wooden bridge. The bridge is weak and only able to carry the weight of two of them at a time. Because they are in a rush and the light is fading they must cross in the minimum time possible and must carry a torch (flashlight,) on each crossing. They only have one torch and it can't be thrown. Because of their different fitness levels and some minor injuries they can all cross at different speeds.

Adam can cross in 1 minute, Bob in 2 minutes, Clair in 5 minutes and Dave in 10 minutes.

What is the minimum time require to cross the bridge?

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Answer:
17 Minutes

Saturday, 30 August 2014

Static program analysis in Java by Findbugs plugin.

Before some days, I was statically analyzing my application code with Findbugs.
During my analysis, I got many warning/bugs/points in my code. From those some are really important which I want to share....
Here are those points.

1.) Bx: Method invokes inefficient Number constructor; use static valueOf instead (DM_NUMBER_CTOR)

Nine(x) ball problem

I have 9 balls, and one ball is heavier than the others, and i have somthing to weight with but we are allowed to use it only twice. How can we know the ball of different weight ?!

Burning Rope/wood puzzle

Question:

I have some number of  non-homogeneous ropes(or woods or fuses), and each one of them needs 1 hr to be burned. Material is non-homogeneous that means if i cut the rope into two equal parts(in the term of length), it is not necessary that both burns in the same time.
(Some may ask about wood(or fuse) instead of rope... but trick is same for solving.)

Q 1.) How can i calculate 45 minutes using those two ropes?!
Q 2.) How can i calculate 15 minutes using only one rope?!

Ans 1:
  1. Fire first rope from both side (front side and rear side) and in parallel start fire in the second rope only from one side.(let say front side)
  2. When one rope will totally burned, on that time start fire in the second rope from rear part. (one rope will totally burn in 30 minutes because as we have double the speed, time taken would be half. It means as one rope needs 1hr to be burn, by doubling the speed so in 30 mins.)
  3. When second rope also totally burn, it would be exactly 45 minutes(because at the end of 30 minutes, it will burn half part, and after that we have double the speed, so at the end of 15 minutes, second rope also totally burned. So total time is 30 minute + 15 minute = 45 minute.)

Frequently asked puzzles during interview

This is a collection of some good interview puzzles which either i have faced or heard from friends.



3.) Crossing the bridge puzzle

4.) 100-coin puzzle

5.) Mislabeled jar - Jelly Beans problem

6.) Red-Blue marble - probability puzzle

7.) Measure "4 liter water" problem

8.) 25 horse, 5 tracks, find 3 fastest horses

9.) Two egg puzzle

10.) Find the celebrity in the party

11.) Find black/white pair of sock

12.) Two door, which path leads to heaven?

13.) 100 door puzzle

14.) Ant and triangle problem

15.) King and wine problem

16.) Gold bar distribution problem

17.) Inverted card puzzle

18.) Pirates profit distribution problem

List updating continuously... :)

Thursday, 14 August 2014

Java Collections - HashMap vs Hastable vs Collections.synchronizedMap vs ConcurrentHashMap

This is a very famous interview topic for the experienced persons who have "really" worked in java technologies. By this question, interviewer can verify weather you have really worked with collections or not also your knowledge on synchronization problem with Hash Map (Collections).

This article can help you for the following questions.
1.) How HashMap works in java.
2.) Have you work with collection classes(HashMap) in the multi threaded environment?
     What are the problems you faced in HashMap? What is ConcurrentModificationException?
     What is fail-fast and fail-safe iterator?
     Why do we need Hashtable or Collections.synchronizedMap Or ConcurrentHashMap?
3.) Similarity/difference between Hashtable and Collections.synchronizedMap.
     If functionality of both (Hashtable and Collections.synchronizedMap) is same then why do we need both?
4.) Similarity/difference between ConcurrentHashMap and Hashtable.
     Similarity/difference between ConcurrentHashMap and Collections.synchronizedMap.
5.) When one can use Hashtable, Collections.synchronizedMap and ConcurrentHashMap.



HashMap
Hashtable
Collections.synchronizedMap
ConcurrentHashMap
Legacy class
-
Yes
-
Java 1.5 and above
Allow
null key/ value
One null key and many null values are allowed.
Not allowed

Allowed
Not allowed
(Neither key nor value)
Thread Safe
No
Yes
Yes
Yes
Lock the entire map?

Yes
Yes
No
(Locks some portion(segment) of the map)
Speed

Slow
(Compare to Concurrent HashMap)
Slow
(Compare to Concurrent HashMap)
Fast
(Compare to Hashtable and Collections.synchronizedMap)
Performance

Low
(Compare to Concurrent HashMap)
Low
(Compare to Concurrent HashMap)
High
(Compare to Hashtable and Collections.synchronizedMap)
Multiple threads can access?
(Is synchronized?)

Yes
Yes
Yes
Multiple threads can access (read) without blocking other thread?

No
(At a time, only one thread can read)
No
(At a time, only one thread can read)

Yes
(At a time, more than one thread can read)
Multiple threads can access (write) without blocking other thread?

No
No
May be
(If writers(threads) write on different segments than only)





Scalable

Less scalable then Concurrent HashMap
Less scalable then Concurrent HashMap
More scalable then Hashtable and Collections.synchronizedMap