Thursday, August 29, 2013

this keyword in Java

The this reference always points to an object’s own instance. Any object can use the this reference to refer to its own instance. Think of the words me, myself, and I: anyone using those words is always referring to themselves. In this post, we'll look into the use of 'this' keyword and it uses in java with example.


What is a class instance
Class instance is an object of a class that you create mostly with the help of 'new' keyword. For instance,
MyClass object = new MyClass();


this Keyword
Within an instance method or a constructorthis is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

Use of this keyword
  1. It clarify that you are talking about a field, when there is another variable of the same name. Some use this as a means to differentiate instance variables from local variables or method parameters.
  2. Refer to current object as stated above
  3. Invoke other constructor of the current class in your parameterized constructor.
  4. It can be used to return the instance of a class
  5. this can also be used to refer to the outer object
Note: One point to remember is that this is associated with the instance of the class, so it will not work in static methods

USING THIS TO ACCESS VARIABLES AND METHODS
You can use the keyword this to refer to all methods and variables that are accessible to a class. For example, here’s a modified definition of the class Employee: 
The variable name can be accessed in the class Programmer (which extends the class Employee) as follows:
Because there exists an object of class Employee within the class Programmer, the variable name is accessible to an object of Programmer. The variable name can also be accessed in the class Programmer as follows:
The this reference may be used only when code executing within a method block needs to differentiate between an instance variable and its local variable or method parameters. But some developers use the keyword this all over their code, even when it’s not required. Some use this as a means to differentiate instance variables from local variables or method parameters

In the previous example, the class Employee defines an instance variable with the name name. The Employee class constructor also defines a method parameter name, which is effectively a local variable defined within the scope of the method block. Hence, within the scope of the previously defined Employee constructor, there’s a clash of names, and the local variable will take precedence. Using name within the scope of the Employee class constructor block will implicitly refer to that method’s parameter, not the instance variable. In order to refer to the instance variable name from within the scope of the Employee class constructor, you are obliged to use a this reference.

USING THIS TO ACCESS CONSTRUCTORS
You can also differentiate one constructor from another by using the keyword this. Here’s an example in which the class Employee defines two constructors, with the second constructor calling the first one:

To call the default constructor (one that doesn’t accept any method parameters), call this(). Here’s an example:

If present, a call to a constructor from another constructor must be done on the first line of code of the calling constructor.

Above can be seen with the help of following example:

Inside a class method, when a local variable have the same name as one of the instance variable, the local variable shadows the instance variable inside the method block.
Download CodeProgrammer.java

If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

Tuesday, August 27, 2013

Thread Communication with Wait(), Notify() & NotifyAll() in Java

In multi-threaded programs, often there is a need for one thread to communicate to another thread. The wait/notify mechanism is useful when threads must communicate in order to provide a functionality. The Object class has three methods, wait(), notify(), and notifyAll() that help threads communicate about the status of an event that the threads care about. In this post, we'll try to create a basic understanding of the most confusing concept of thread communication using methods wait(), notify() and notifyAll(). If you want to go through the Thread basic check this post


Classes that provide necessary support for concurrency in Java
  • Object : has methdods wait(), notify(), notifyAll() etc which are useful for multi-threading.
  • Thread Class
  • Runnable interface
As you every class extends Object class, so all object have some basic multi-threading capability.


In multi-threaded programs, often there is a need for one thread to communicate to another thread. The wait/notify mechanism is useful when threads must communicate in order to provide a functionality.
The method wait() allows the calling thread to wait for the wait object (on which wait() is called). In other words, if you want to make a thread wait for another thread, you can ask it to wait for the wait object using the wait() method. A thread remains in the wait state until some another thread calls the notify() or notifyAll() method on the wait object.


**One key point to remember (and keep in mind for the exam) about wait/notify is this:
wait() notify() and notifyAll() must be called from within a synchronized context! A thread can't invoke a wait or notify method on an object unless it owns that object's lock

Note that if the thread calling wait() does not own the lock, it will throw an IllegalMonitorStateException. This exception is not a checked exception,so you don't have to catch it explicitly. You should always be clear whether a thread has the lock of an object in any given block of code.


Let's first go through a basic example
I have on thread ThreadB other than main thread that calculate the sum of number meanwhile main() thread wait for ThreadB to notify when calculation is doneIt may look complex to you first time if you are using notify(), wait() methods first time. So keep patience!


Try to run the code and observe the output:


In the above example, main thread is waiting for threadB to complete. When ThreadB complete the processing it notify the main thread with notifyAll() method.

This how wait() and notify() communicate..!

May be some of you wondering above sceanrio can be implemented with the help of join() method?
Yes, that's true, see the below example



** The wait() and notify() methods are designed to provide a way to allow a thread to block until specific condition is met. For instance, In case of producer consumer problem, there will be a specific condition where producer or consumer wait i.e, when queue is empty consumer will wait and when queue is full producer will wait.
So,the first thing you have to do is to identify the conditions that you want the methods to wait for.

Following thing to remember while using wait and notify or notifyAll method in Java

  • use notifyAll instead of notify if you expect more than one thread is waiting for lock.
  • wait and notify method must be called in synchronized context
  • use same object for calling wait() and notify() method, every object has its own lock so calling wait() on object A and notify() on object B will not make any sense.

Wait() does not block the thread on which it is called; it blocks the current thread until notify() is called on the same object.
For instance, If you have threads A and B and, while in thread A, called B.wait(), this will stop thread A and not thread B - for as long as B.notify() is not called.

If you still having doubt till this line, please go again before going further because if you are clear about the above point then it will be easy to understand.

Now we'll take an example where two thread communicate where these two thread print the integer value from 1,2,3 ...so on turn by turn.
As I said earlier we need specific condition where these thread will wait for other, so in this example we take a Boolean variable as a specific condition where thread will wait. When it's value is true one thread will wait and when it's false other will wait.

Now see the below example that I created


Execute the above code and observe the output and try to add comments to see the flow as per your need to clear doubt.

Coffee Shop Simulation 
To further understand the wait/notify mechanism, you are going to simulate this coffee shop situation in a program. You can implement the coffee machine as one thread and the waiter as another thread in two different classes. The coffee machine can notify the waiter to take the coffee, and it can wait until the waiter has taken the coffee from the tray. Similarly, the waiter can take the coffee if it is available and notify the coffee machine to make another cup.


Producer Consumer problem
Producer Consumer is one of the classical concurrency problem. As there are many way to solve this problem, here I explained with help of wait(),notify() methods.
In the following code, ArrayList is take as source where producer can put the data and from where consumer consume the data. Here I'm adding one 5 values in ArrayList instead of adding infinite value for the demo purpose. If you understand the example, then you can modify and try yourself

Simulation on the basis of Name of player
As we have already seen the example above where thread printing the value turn wise. Now we implement the same in different way.
Now there will be two player, who will increment the value turn wise. Now the specific condition will be player name instead of boolean flag. Instead of creating ThreadFirst and ThreadSecond we'll create only one Thread and two instance of the same thread will be used.

This way you can implement the previous problem also.
I hope so you got the idea how we use notify(), notifyAll() and wait() methods to implement thread communication.
Best of luck!

When to use notify() and notifyAll()?
Let's examine the subtle difference between these two calls. The notify() method wakes up one thread waiting for the lock (the first thread that called wait() on that lock). The notifyAll() method wakes up all the threads waiting for the lock; the JVM selects one of the threads from the list of threads waiting for the lock and wakes that thread up.

In the case of a single thread waiting for a lock, there is no significant difference between notify() and notifyAll(). However, when there is more than one thread waiting for the lock, in both notify() and notifyAll(), the exact thread woken up is under the control of the JVM and you cannot programmatically control waking up a specific thread.


At first glance, it appears that it is a good idea to just call notify() to wake up one thread; it might seem unnecessary to wake up all the threads. However, the problem with notify() is that the thread woken up might not be the suitable one to be woken up (the thread might be waiting for some other condition, or the condition is still not satisfied for that thread etc). 
In that case, the notify() might be lost and no other thread will wake up potentially leading to a type of deadlock (the notification is lost and all other threads are waiting for notification—forever!).


To avoid this problem, it is always better to call notifyAll() when there is more than one thread waiting for a lock (or more than one condition on which waiting is done). the notifyAll() method wakes up all threads, so it is not very efficient. however, this performance loss is negligible in real world applications.

Related Post:
Daemon Thread in Java with Example
Detail info of Garbage Collection in Java
Basic concept of Thread in java
Interview 120+ Core java Question Answers


If you know anyone who has started learning Java, why not help them out! Just share this post with them. 
Thanks for studying today!...

Monday, August 26, 2013

Basic of Thread in Java

Processors these days have multiple cores, which are multiple execution units in the same processor. To make the best use of these multi-cores, we need to run tasks or threads in parallel. In other words, we need to make our programs multi-threaded (or concurrent).
Multiple threads can run in the context of the same process and thus share the same resources. How multiple thread share same resource you check this post Heap and Memory.

Performing activities in parallel enhances the responsiveness of the application, and thus the user experience.Such parallel activities can be implemented as threads: running multiple threads in parallel at the same time is called multi-threading or concurrency.
For instance, MS word office executed many task at the same time - responding to the user, checking spellings, carrying out formatting and certain associated background tasks, etc. That only possible with multiple threading.
thread




Classes that provide necessary support for concurrency in Java

  • Object : has methdods wait(), notify(), notifyAll() etc which are useful for multi-threading.
  • Thread class
  • Runnable interface

As you every class extends Object class, so all object have some basic multi-threading capability.

Methods detail that are helpful in Multi-threading

Method Method Type Short Description
Thread currentThread() Static method Returns reference to the current thread.
String getName() Instance method Returns the name of the current thread.
int getPriority() Instance method Returns the priority value of the current thread.
void join(),                    void join(long),                   void join(long, int) Overloaded
instance methods
The current thread invoking join on another thread waits
until the other thread dies. You can optionally give the
timeout in milliseconds (given in long) or timeout in
milliseconds as well as nanoseconds (given in long and int).
void run() Instance method Once you start a thread (using the start() method), the
run() method will be called when the thread is ready to
execute.
void setName(String) Instance method Changes the name of the thread to the given name in the
argument.
void setPriority(int) Instance method Sets the priority of the thread to the given argument value
void sleep(long),          void sleep(long, int) Overloaded static
methods
Makes the current thread sleep for given milliseconds
(given in long) or for given milliseconds and nanoseconds
(given in long and int).
void start() Instance method Starts the thread; JVM calls the run() method of the
thread.
String toString() Instance method Returns the string representation of the thread; the string
has the thread’s name, priority, and its group.

Method Method Type Short Description
void wait(),
void wait(long),           void wait(long, int)
Overloaded instance
methods
The current thread should have acquired a lock on this
object before calling any of the wait methods.
If wait() is called, the thread waits infinitely until some
other thread notifies (by calling the notify()/notifyAll()
method) for this lock.
The method wait(long) takes milliseconds as an argument.
The thread waits till it is notified or the timeout happens.
The wait(long, int) method is similar to wait(long) and
additionally takes nanoseconds as an argument.
void notify() Instance method The current thread should have acquired a lock on this
object before calling notify(). The JVM chooses a single
thread that is waiting on the lock and wakes it up.
void notifyAll() Instance method The current thread should have acquired a lock before
calling notifyAll(). The JVM wakes up all the threads
waiting on a lock.



Basic ways to create thread?
  • By extending the Thread class
    You need to override the run() method when you want to extend the Thread class. If you don’t override the run() method, the default run() method from the Thread class will be called, which does nothing.
  • By implementing the Runnable interface
    The Thread class itself implements the Runnable interface. Instead of extending the Thread class, you can implement the Runnable interface. The Runnable interface declares a sole method, run()
Note: run() method should be declared as public void run().

Should you extend the Thread or implement the Runnable?
Since Java supports only single inheritance, if you extend from Thread, you cannot extend from any other class. On the other hand, if you implement the Runnable interface, you can still extend some other class. So, many Java experts suggest that it is better to implement the Runnable interface unless there are some strong reasons to extend the Thread class.
Why we call start() methods instead of run() method?
First we see one example:




public class MyFirstThread extends Thread {
  public void run() {
   System.out.println("In run method; thread name is: " +
    Thread.currentThread().getName());
 }
 public static void main(String args[]) throws Exception {
  Thread myThread = new Thread(new MyFirstThread());
  myThread.run(); // note run() instead of start() here
  System.out.println("In main method; thread name is : " +
    Thread.currentThread().getName());
 }
}



Output :

In run method; thread name is: main

In main method; thread name is : main

The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run() method returns. On the other hand if you can run() directly, it simply executes as part of the calling thread.It does not execute as a thread: it doesn't get scheduled and get called by the JVM

That is why the getName() method in the run() method returns “main” instead of “Thread-0.” When you call the start() method, the thread gets scheduled and the run() method is invoked by the JVM when it is time to execute that thread.

**Never call the run() method directly for invoking a thread. Use the start() method and leave it to the JVM to implicitly invoke the run() method. Calling the run() method directly instead of calling start() is a mistake and is fairly common bug.


Thread Name, Priority, and Group
Every thread has a name, which you can used to identify the thread. If you do not give a name explicitly, a thread will get a default name. The priority can vary from 1, the lowest, to 10, the highest



class SimpleThread {
public static void main(String []s) {
 Thread t = new Thread();
 System.out.println(t);
 }
}

This program prints the following:
Thread[Thread-0,5,main]

Explanation: default name Thread-0,The default priority is 5,default thread group is main.

You can change the same like this
t.setName("SimpleThread");
t.setPriority(9);


The States of a Thread
A thread has various states during its lifetime.You’ll see three thread states—new, runnable and terminated—which are applicable to almost all threads


How to access thread state in a program?
  • Thread.State enumeration
  • getState() instance method
Two States in “Runnable” State
  • ready state 
  • running state 
A thread is in the ready state when it is waiting for the OS to run it in the processor. When the OS actually runs it in the processor, it is in the running state
Basic Thread state example:

class BasicThreadStates extends Thread {
 public static void main(String []s) throws Exception {
  Thread t=new Thread(new BasicThreadStates()); 
  System.out.println("Just after creating thread; \n" +"The thread state is: " + t.getState());
  t.start();
  System.out.println("Just after calling t.start(); \n" +"The thread state is: " + t.getState());
  t.join();
  System.out.println("Just after main calling t.join(); \n" +"The thread state is: " + t.getState());
 }
}





timed_waiting and blocked States
Example:


class SleepyThread extends Thread {
 public void run() {
  synchronized(SleepyThread.class) {
   try {
    Thread.sleep(1000);
   }
   catch(InterruptedException ie) {
    ie.printStackTrace();
   }
  }
 }
}
class MoreThreadStates {
 public static void main(String []s) {
  Thread t1=new SleepyThread();
  Thread t2 =new SleepyThread();
  t1.start();
  t2.start();
  System.out.println(t1.getName()  +": I'm in state " + t1.getState());
  System.out.println(t2.getName()  +": I'm in state " + t2.getState());

  }
}


Output will look like :
Thread-0: I'm in state TIMED_WAITING
Thread-1: I'm in state BLOCKED


Concurrent Access Problems
Threads share memory, and they can concurrently modify data. Since the modification can be done at the same time without safeguards, this can lead to unintuitive results.

Data Races or Race condition or Race hazard
When two or more threads are trying to access a variable and one of them wants to modify it, you get a problem known as a data race.

Let see with an example:
class Counter {
 public static long count = 0;
}
class UseCounter implements Runnable {
 public void increment() {
  Counter.count++;
  System.out.print(Counter.count + " ");
 }
 public void run() {
  increment();
  increment();
  increment();
 }
}
// This class creates three threads
public class DataRace {
 public static void main(String args[]) {
  UseCounter c = new UseCounter();
  Thread t1 = new Thread(c);
  Thread t2 = new Thread(c);
  Thread t3 = new Thread(c);
  t1.start();
  t2.start();
  t3.start();
 }
}


when you run this program, it does print nine integer values, but the output looks like
3 3 5 6 3 7 8 4 9

The expression Counter.count++ is a write operation, and the next System.out.print statement has a read operation for Counter.count. When the three threads execute, each of them has a local copy of the value Counter.count and when they update the counter with Counter.count++, they need not immediately reflect that value in the main memory .In the next read operation of Counter.count, the local value of Counter.count is printed.

To avoid this problem, you need to ensure that a single thread does the write and read operations together.The section of code that is commonly accessed and modified by more than one thread is known as critical section.

Now Synchronization will come into picture.

Thread Synchronization
Java has a keyword, synchronized, that helps in thread synchronization
Use of synchronized keyword:
  • synchronized blocks
  • synchronized methods


synchronized blocksIn synchronized blocks, you use the synchronized keyword for a reference variable and follow it by a block of code. A thread has to acquire a lock on the synchronized variable to enter the block; when the execution of the block completes, the thread releases the lock. 

synchronized(this) {
// code segment guarded by the mutex lock
}
What if an exception gets thrown inside the synchronized block? Will the lock get released? 

Yes, no matter whether the block is executed fully or an exception is thrown, the lock will be automatically released by the JVM.
With synchronized blocks, you can acquire a lock on a reference variable only. If you use a primitive type, you will get a
compiler error.

int i = 10;
synchronized(i) { /* block of code here*/}



synchronized methodsIn entire method can be declared synchronized. In that case, when the method declared as synchronized is called, a lock is obtained on the object on which the method is called, and it is released when the method returns to the caller.
A synchronized method is equivalent to a synchronized block if you enclose the whole method body in a synchronized(this) block.


Synchronized Blocks vs. Synchronized Methods
If you want to acquire a lock on an object for only a small block of code and not the whole method, then synchronized blocks are sufficient; using synchronized methods is overkill in that case.In general, it is better to acquire locks for small segments of code instead of locking methods unnecessarily, so synchronized blocks are useful there. 

In synchronized blocks, you can explicitly provide the reference object on which you want to acquire a lock. 
However, in the case of a synchronized method, you do not provide any explicit reference to acquire a lock on. A synchronized method acquires an implicit lock on the this reference.


Deadlocks
Obtaining and using locks is tricky, and it can lead to lots of problems. One of the difficult problems is known as a deadlock.

A deadlock arises when locking threads result in a situation where they cannot proceed and thus wait indefinitely for others to terminate.Say, one thread acquires a lock on resource r1 and waits to acquire another on resource r2. At the same time, say there is another thread that has already acquired r2 and is waiting to obtain a lock on r1. Neither of the threads can proceed until the other one releases the lock, which never happens—so they are stuck in a deadlock.




Let's take an example from cricket game. In this, we have two resources one will hold the total numbers of balls thrown so far and other to hold numbers of runs scored so far.






/*
 * Hold number of balls
 */
class Balls{
 public static int balls=0;
}
/*
 * Hold number of runs
 */
class Runs{
 public static int runs=0;
}

class CricketCounter implements Runnable{
 public void run() {
  IncrementRunAfterBall();
  IncrementBallAfterRun();
 }

 public void IncrementRunAfterBall(){
  //since we are updating balls first
  synchronized (Balls.class) {
   System.out.println(Thread.currentThread().getName()+" waiting for run resources");
   synchronized (Runs.class) {
    Balls.balls++;
    Runs.runs++;
   }
  }
 }

 public void IncrementBallAfterRun(){
  //since we are updating Runs first
  synchronized (Runs.class) {
   System.out.println(Thread.currentThread().getName()+" waiting for ball resources");
   synchronized (Balls.class) {
    Runs.runs++;
    Balls.balls++;
   }
  }
 }

}
public class DeadlockDemo {
 public static void main(String[] args) {
  CricketCounter c= new CricketCounter();
  Thread t1=new Thread(c);
  Thread t2=new Thread(c);
  t1.start();
  t2.start();
 }

}

Sample Output

Thread-0 waiting for run resources
Thread-1 waiting for run resources
Thread-0 waiting for ball resources


From the above output, you can easily see that both the thread has already acquired the Balls resources and Thread-0 acquired the Runs resources and Thread-1 waiting for Runs resources that is already acquired by other thread-0.

When the threads t1 and t2 execute, they invoke the methods IncrementBallAfterRun and IncrementRunAfterBall. In these methods, locks are obtained in opposite order. It might happen that t1 acquires a lock on Runs.class and then waits to acquire a lock on Balls.class. Meanwhile, t2 might have acquired the Balls.class and now will be waiting to acquire a lock on the Runs.class. Therefore, this program can lead to a deadlock 




Related Post:
Daemon Thread in Java
Thread communication with wait(), notify(), notifyAll()
Detail concept of class loader in Java
Interview related concept of Garbage Collection in java

If you know anyone who has started learning Java, why not help them out! Just share this post with them.Thanks for studying today!...