Wednesday, October 9, 2013

WAIT() NOTIFY() SHORTCOMING: SINGLE WAIT QUEUE

There is an inherent drawback of wait(), notify() methods in Java.
As we are aware every Object in Java is associated with a Entry Queue and a Wait Queue. When a thread reaches a synchronized block, it will wait on the Entry Queue of the Object if any other Thread already has the lock. Once it acquires the lock, does its processing, calles Object.wait(), it waits on Wait Queue of the Object. When some other Thread calls Object.notify(), one of the threads waiting on the Wait Queue is moved to the Entry queue of the Object, where it fights for the lock on the Object (with all other Threads waiting at the Entry Queue).
The shortcoming is that wait is not a conditional wait. Every object has just one wait queue.
So if a Object.notify() is called, of all threads waiting on wait queue, any one thread at random is moved to the entry queue. There is no direct way to notify a particular Thread. What we do is a workaround. Instead of Object.notify(), we call Object.notifyAll(), so as all threads are moved from Object’s wait queue to entry queue. Object.wait() call is made in a while loop each checking on a particular condition. So we attach each Object.wait() with a particular condition, as below.
1
2
3
4
5
6
7
8
9
10
11
12
13
//Thread1
synchronized(object) {
    while(!condition1) {
        object.wait();
    }
}
//Thread 2
synchronized(object) {
    while(!condition2) {
        object.wait();
    }
}
When some other Thread sets condition2 = true (while condition1 is still false) and calls object.nofityAll(), both the above Threads which are waiting on the wait queue of the object, are moved to entry queue of the object. Since wait() is in spinning while loop, so Thread1 (if it gets the lock) again calls object.wait() while the Thread2 (if it gets the lock) comes out of the loop starts the processing.
The drawback you see, is unnecessary processing (looping once and checking for condition) in Thread1 and also unnecessary moving of Thread1 from wait queue of Object to entry queue to back. Thread1 wanted to awaken only ifcondition1 == true and Object.notify() is called (not just @ Object.notify()). What would have been nice if there was provision for Conditional Monitor Objects with each having its own wait queue. Something like,
1
2
3
4
5
6
7
8
9
//Thread 1
synchronized(object) {
    object.wait(condition1);
}
//Thread 2
synchronized(object) {
    object.wait(condition2);
}
Here wait is now waiting on a condition. I have seen some good implementations which are provided  for above problem. One being here.

Tuesday, August 6, 2013

THREAD SLEEP/WAIT

Oxford Dictionary defines wait and sleep as below:
wait: delay action until (someone) arrives or is ready.
sleep: a condition of body and mind which typically recurs for several hours every night, in which the nervous system is relatively inactive and consciousness practically suspended
Wait is to not act till someone arrives. Sleep is to not act for a specified time. It’s amazing how much dictionary meaning of words can tell you about their technical aspects.
Wait and Sleep are confusing terms. A wife falls asleep waiting for the husband to be back from office. Isn’t sleep just a wait to wake up again. Aren’t they interchangeable terms? Which holds lock on the monitors? Which consumes CPU cycles? Lets’s explore.
One important concept to be understood before moving forward is Context Switching: When multiple processes share a single CPU, they fight for the CPU time. It is via context switching that each of them gets some CPU time slice. In very basic terms, one process should be switched out of CPU so that another process can run. Similar context switching can be understood at the JVM level for a single process which has many threads.
To begin with we need to define, the States of a Thread in Java.
  1. RUNNABLE: Thread executing in JVM (might not execute in OS, as OS might make it wait for the processor, say)
  2. WAITING: Waiting ad infinitum for some other thread to perform some action. If current Thread callsObject.wait(), it is WAITING for some other thread to call Object.notify().
  3. BLOCKED: Waiting to get monitor lock
    • Either waiting to enter synchronized block, or
    • In Waiting state of Current Thread, if some other thread calls Object.notify(), the Current Thread moves to BLOCKED state and fights for the monitor lock. If some other Thread gets the lock, current Thread goes back to WAITING state.)
  4. TIMED_WAITING: 
    • Waiting for a specified time interval (Thread.sleep(TIMEOUT)) or
    • Waiting for some other Thread to call Object.notify() or for a specified time interval, whichever is shorter (Object.wait(TIMEOUT)).
What happens when Thread.sleep(TIMEOUT) is called? TIME-SYNCHRONIZATION
  1. The running Thread is forcefully switched out (context switching) and put in TIMED_WAITING state for the specified interval.
  2. As name suggests, it simply sleeps and require no CPU time-slice. Theoretically speaking, if this is the only process running and you put Sleep statements with substantial TIMEOUT, you will notice drop in CPU usage. Short bursts of continuous sleep statements, might increase CPU usage as Context Switching incurs its own cost.
  3. Once the Sleep time is over, Thread is scheduled back to be executed. However there is no guarantee that  Context Switching will happen immediately. Depends upon the resources available. If a high priority work is going on, this Thread will not get CPU time instantaneously. If will be scheduled no doubt, but when it will be executed comes with no guarantee.
  4. Sleep can be interrupted by Thread.interrupt(). This caused InterruptedException to be thrown. It is normally used to HALT the operations.
  5. If sleep is called from a synchronized block (say). No other Thread can enter this block. Thread holds the ownership (lock) of the monitor object.
  6. sleep is a static method. If we call diffThread.sleep from the current Thread, it wont halt diffThread. It is the current Thread which will sleep.
What happens when Object.wait() is called from inside the synchronized block? MULTI-THREAD SYNCHRONIZATION
  1. The running Thread is switched out (context switching) and goes to the WAITING state .  In WAITING state, itrequires no CPU time-slice.
  2. In Java every Object is associated with two queues, wait queue and entry queue. Post Object.wait() Thread waits on the wait queue of the object.
  3. The Thread will hold no lock on the monitor object. Any other thread can enter the synchronized block.
  4. It will remain in WAITING state until some other Thread which will synchronize on the same object, calls Object.notify()
  5. Once Object.notify() is called, of all Threads that are WAITING on the same monitor object, one is awakened at random and is moved to BLOCKED state (Moved from waiting queue of object to entry queue of the object), where it tries to get the lock on monitor object. It has to fight with other Threads BLOCKED on the same Object. Once it gets the lock, it is scheduled to be executed by the CPU, again with no guarantees when.
  6. If 10 Threads have called Object.wait() on the same object, Object.notifyAll(), awakens all 10 threads and move them in BLOCKED state where they fight with other BLOCKED Threads for the lock on the object  One of these 10 might get the lock (some other Thread which was BLOCKED to enter the  synchronized block, might just get the lock) and rest 9 go back to the WAITING state (in effect waiting Queue of the Object) till they get the next notify signal.
  7. In BLOCKED state Thread incurs CPU cost as it tries to get the lock. JVM might try to get to acquire monitor lock multiple times before context switching it OR JVM might context switch it just after one try. It depends on Algorithm implemented at JVM level.

Friday, July 12, 2013

15 Mandatory Core Java Interview Questions - Part 2

15 Mandatory Core Java Interview Questions - Part 1

16. What is Java Byte Code?

JVM does not understand *.java files. JDL compiled *.java files and create *.class files, which contain bytecode and understood by JVM. If we take the same bytecode and run it on different enviroments, due to the JVM which is uniform, we will get same results.

This make life simpler for developers,  isn’t it? Why worry about where the code will run. Just write the code and be done.

Compiler compiles the code in a bytecode for a Virtual Processor (JVM) which in turn converts it into Machine code for a Real Processor (LinuX/Windows platform).

17. Can we define main() as private?

Yes, It can be defined as private. Program will compile fine. But we will get a runtime Error.



18. Differentiate between final, finally, finalize.

final: final variable cannot be changed once initialized, final method can't be overridden, final Class can't be extended.

finally: code inside finally block executes after the try block (Even when there is an exception). Clean up code is normally put inside finalize to close open references in case of Exceptions.

finalize: This method is at Object level. When the Object is Garbage collected, this method is called. This method is overridden in special circumstances only for system resources clean-up.

19. List down the OOPs concepts.

a) Polymorphism
b) Inheritance
c) Encapsulation

20. Explain the concept of Polymorphism.

Well as name suggests, Polymorphism means poly-forms, means Many Forms. When same name is used in many forms, we call it polymorphism. Same entity can be used for multiple actions. It happens with Method Overloading and Method Overriding.

21. Explain the concept of Inheritance.

In Java, once class can acquire properties of another class via inheritance. Sub class (which acquires properties) inherits all methods of Super Class (parent class), In Java Only Single inheritance is allowed. A class can extend only one class.

22. Explain the concept of Encapsulation.

Encapsulation is what Java Class stands for. The data of an Object is kept safe from outside world via encapsulation. Access to it is regulated, public/private/protected modifiers are used to regulate the access. It is like putting a child in a protective wool wrap to protect him/her from the world.

23. What happen if within static context, we call non-static variable.

This will result in an Error. Static Variable belongs to the Class. This variable is initialized when Clss is loaded. At that time the Object of the class is not created. Hence we will get an Error while compilation as non-static variable does not exist at that time.



24. What is Pass by reference, Pass by value?

When an object is passed during the function call, either a replica of that object can be passes or the memory location of that object (reference) can be passed.

When passed by value, the original object is safe. Any alteration to the passed object is not reflected back to the original object. When passed by reference, original object is worked upon and all changes are reflected back.

25, Is Java Pass by Value or  Pass by Reference?

Java is Pass by Value. Period.
You will find a lot of literature on this across the spectrum, bottom line is java is just pass by value. For primitive types, the value is copied over while calling a method. For user define data types, address of the memory where the object is stored is pass by value. We don't call it pass by reference as reference is like a constant pointer (we cannot reassign a reference once assigned).

26. Can constructor be overloaded in Java?

Yes, constructor overloading is permitted in Java. Each constructor need to have it's own unique parameter list.

27. De-construct and explain public static void main (String args[]).

public: main() needs to be called by JVM outside the application, hence it needs to be public
static: main() needs to be called before instantiating any object, hence it is static
void: main() is designed not to return anything hence void
String args[]: main takes as input stream of input from cmd line (as string).

28. How to calculate size of an object in Java?

Java does not have a sizeof type Operator that is present in C. Calculating the size of a User Defined Object is tricky and we are just able to approximate by calculating size of member variables. No straightforward approach. It leads me to say that Java designers didn't think we would need to calculate the sizeof Object as memory allocation/deallocation is done by Java rather than the user.

29. Explain System.out.println

System is a final class from java.lang package. out is a public member variable of System class, of type PrintStream. println is a public method of PrintStream class.

30. Can we have global variables in Java?

The answer is No. By design global variables does not exist in Java. They create unnecessary nuisance. We can use public final static which can be used as Global Constants in a separate Class (say Constants.java). We can use like Constants.x, Constants.y.





Saturday, June 8, 2013

15 Mandatory Core Java Interview Questions - Part 1

1. What is the Object class?

java.lang.object is the superclass of all Classes in java. All classes extend this implicitly, hence All Classes isA Object. They show Object behaviour.

In the sense that all methods in Object classes are available to all classes in Java.


Object of any class can be assigned to Object.



2. Is Java Truly and Object Oriented Language?

Yes, Java is an Object Oriented language but not a pure one. Question arises Why? It is because java supports primitive datatypes like int, float, double. We have wrapper classes Integer, Float, Double also, but for simplicity it also supports primitive classes.

3. Why is main() method static in Java?

Main() method is the entry point of any program. It is loaded before any Class Object is created. Since Static function can be accessed directly from Class level and don't need an object creation. In short, main() is called before Object creation, hence main() is static.

4. Is overloading main() supported?

Yes. main() function can be overloaded. Read here for more details.

5. Explain Method Overloading and Overriding.

When multiple methods in the same class have the same name, it is called method overloading. Function arguments list can differ.
When a subclass, redefine a method present in parent class, it is called Method Overriding. Function name, arguments and return type needs to be the same while Overriding.

6. Example of Multiple Inheritance in Java?

Multiple Inheritance is not allowed in Java. A class cannot extend multiple classes but can implement multiple interfaces. 

7. Difference between JDK, JRE, JVM.

Java Virtual Machine (JVM) is a layer on top of the real hardware. For those who interact with it, JVM acts as though it is the real boss (Machine). But in reality it’s just a Software Hoax on which program is executed. It makes Java platform independent.

Various implementations of JVM which are installed on various Platforms are called JRE (Java Runtime Environment). This is the software which runs and interact with the Real Hardware and provide a JVM. It also contains the libraries required to run applications.

JDK contains JRE, JVM and compiler (javac.exe) along with other things. With JDK one is able to compile (convert *.java to *.class bytecode) and run (java.exe) a program.

For more details read JDK-JRE-JVM.

8. Explain static member/method in Java?

static member/method in Java, can be accesses without instantiating a class and loading an Object of that class. (Class.method). An important quality of static method is that it cannot be overridden. Overriding is resolved runtime with class Objects. Since with static the concept is different, hence overriding is not possible.

9.  What are the primitive data types supported in java?

Below are the data types in Java. For more details read. primitive data types java.

Data Type
Size
Default Value
Min
Max
boolean
1 bit
false
false
true
char
2 byte
'\u0000'
'\u0000' (or 0)
'\uffff' (or 65,535)
byte
1 byte
0
-128 (-2^7)
127 (2^7 -1)
short
2 byte
0
-32,768 (-2^15)
32,767 (2^15 -1)
int
4 byte
0
- 2,147,483,648 (-2^31)
2,147,483,647 (2^31 -1)
long
8 byte
0L
-9,223,372,036,854,775,808
(-2^63)
9,223,372,036,854,775,807
(2^63 -1)
float
4 byte
0.0f


double
8 byte
0.0d



10. How can you define a class as static?

Class as such can't be define as static. All methods/members can be defined as static. We can call such a class as static.
However inner classes can be defined as static. 

11. What all datatypes can be used in switch/case?

A serious drawback of Switch-Case was it just worked with expressions that evaluated to int (int, short, byte, char, Enum). Not anymore. With Java 7 it can take Strings too. Isn’t is awesome?
String fruit = "apple";
switch (fruit) {
case "orange":

12. Give an example of Marker Interface.

Serilaizable/Cloneable are two famous examples of Marker Interface. They are empty interface with no methods inside, but are used to enabling some functionality in the implementing classes.



13. What is the difference between sleep/wait?

Difference in Sleep and Wait

14. Give a usage of instanceof Keyword.

instanceof keyword is used to check if a given Object belongs to a particular class or not. It becomes useful in case of inherited classes. All objects are instanceof Object class.



15. What is Thread in Java?

Thread relates to running of a program. A Thread is a single chain of execution within a program. click here for more details.


Sunday, May 12, 2013

DEPENDENCY INVERSION (D INV)

To put it straight, DI = IoC + D Inv. How? Lets explore.
Before the helper and DI were introduced, Hands/Legs/Face were designed first. When Body was created it just used new Hands/Legs/Face. Body does not dictate the design of Hands or Legs. Suppose Hands were designed to have teeth. Body can’t dictate that Hands should not have Teeth (High level module can’t interfere with design of Low level module, it can just use it). There are there and Body has to live with it. So everyone will eat off their hands, literally.
Programming wise Body is High Level Component and Hands are Low Level Component and are kept in separate packages. Body Component Package depended upon Hand Component Package for compilation. Thus HLC depends upon LLC for compilation.
DInv says other wise. Low Level Components (Hands) also need to confirm  to some abstraction (Hands have to be type of SomeHands, so now we have SmallHands, ThinHands and also TeethHands which are type of SomeHands, but NOT all Bodies need to have TeethHands). Body is also bound by SomeHands. It can’t fit ShortLeg instead of SomeHands.
DInv says both Low Level and High Level modules need to confirm to some abstraction.
Programming wise, this is achieved by separating High Level component  (Body) and Low Level component  (Hands) into separate packages. And the Interfaces (SomeHands, SomeLegs) defining the Behavior/Services which the HLC needs are inside HLC package and are owned by it. Here LLC implement the interfaces owned by HLC. Thus LLC depend on HLC for compilation. Thus usual Dependency relationship is INVERTED.

Saturday, March 23, 2013

Reverse a String in Java

How to reverse a String in java?

Input: javaonjava
Output: avajnoavaj

Well there are some complex approaches to it. Storing the String as character array and then reverse the character array. Convert it back to String.

But since Java is Java. We have all the support available.




Wednesday, March 20, 2013

DEPENDENCY INJECTION (DI)

What I feel is people understand Dependency Injection (DI) more than Inversion of Control (IoC). When I ask in an interview, “What have you used spring for?”. The answer normally is, “I have used it for IoC” or “I have used it for DI”. But when I ask the difference between IoC and DI, I mostly  get the answer, “They are the same” or “DI was earlier called IoC”.
What really is DI? Is it the really new name for IoC? Is there any difference between DI and IoC? Lets try and explore there questions.
Let me begin by stating that DI is not the new name of IoC. DI is something which affirms to IoC concept. When we do DI, we are doing IoC (Not the other way round). Following IoC does not mean DI would have happened. DI is just one of the ways to achieve IoC.
Example: God creating Man
When God creates Man. He would start with an Empty Body (Body Class). Then he would create new Hands, new Legs, new Face inside the Body (inside Body constructor). This Body now has to live with whatever Hands, Legs, Face were created (Tightly coupled). But no one can refute that a Man is created alright.
Now if God wants to create another Man (He would need to do so a lot, given there are 6 billion of us on this planet, and we are born regularly), God will start with another empty Body and try and put different features to it. Say SmallHands, RoundFace, LongLegs.
So now God will keep on creating new Bodies (class Body1, class Body2, class Body3) etc. Poor God!
How nice it would have been, had God just created one Body (written one Body class) and said that it will have SomeHands, SomeFace and SomeLegs.
How nice it would have been had God had a helper (Framework like Spring), who would create different Hands (SmallHands, LongHands), different Faces (RoundFace, SquareFace). He would just copy the generic Body God created and will insert these Hands/Legs/Face to it independently. Good for God!
This is called Dependency Injection, where dependencies (on which Body depends) are not created (inside constructor) when Body is created by God. They are instead created and fitted when Body needs to be sent to Earth.
This affirms to IoC as control of creating new Type of Hands/Face/Legs lie not with the God but with the Helper who makes job of God easier,
This is what they call “Don’t call us, We’ll call you” (Hollywood Principle). Body, please dont call Hands() constructor to create new Hands, instead when Helper needs a Body() to be sent to Earth,  it will create new Hands(), will then call Body and inject the Hands.

Tuesday, January 1, 2013

INVERSION OF CONTROL (IOC)

The more I read about IoC, the more it gets complicated. One thing gets clear though, it is one of the the most misunderstood terms. More often than not, it is confused to be an old name for Dependency Injection (DI). Also people tend to understand it directly via some Code Snippet or via its implementation by any Framework.
In reality it’s just a concept borne out of some one’s imagination one fine day. Hence it should be understood irrespective of any code/framework. First came the logic and then came the code.
Most of the people I meet at workplace, have started off their careers by reading a Java or C++ book before they started to code at workplace.
My case have been the other way round. I started off my career without reading any language specific book per say. I googled knowledge out of internet as per the need arose.
I think this would be an apt example of Inversion of Control. Instead of a Book controlling what I learn and in which sequence. I was in the control of what I needed to learn. Googling (Sending Event) about a particular topic as and when required, I learned that topic (Note: The explanation of topics on Google  is eventually the same as in the book).
To be more specific, the e-version of a book v/s printed version. In e-version, I can search the topic I want to read. So the control moves from book (printed version) to the user (e-version)
Thus the Control got INVERTED.
Examples:
1. GMAT vs CAT
Another good example that I can think of IoC is GMAT exam vs CAT exam. Those who have taken GMAT would understand this better. A question pops up, you have answer it. Then only you can move to the next question. You can’t skip and come back later to the same question. The control is with the Application (GMAT Software).
Consider at the same time CAT Online Exam. We can skip questions, come back later. Choose what question to solve when. Thus some control is shifted to the person who is taking the Exam (Inversion of Control).
2. Simple Delivery vs Midnight Delivery
Another Example is Simple vs Midnight Delivery Service. In simple service, we book a courier. It is upto the delivery guy at what time he will deliver within the SLA.
Midnight Delivery Service is when we want to send our Girl Friend flowers at midnight. Here we are able to set the time when the Delivery guy should deliver (midnight). We can even call the Delivery person and specify/change the timing. Some control shifts from the wish of Delivery Guy to us.
Complete IoC will happen if say someone has sent us a courier. When we get home, we call up the delivery guy and say , “Now I am home, you come and deliver”.