Showing posts with label Threads. Show all posts
Showing posts with label Threads. Show all posts

Monday, 8 April 2013

How to get current stack trace in Java for a Thread

Leave a Comment
 what is stack trace in Java

Thread executes code in Java, they call methods, and when they call, they keep them in there stack memory. You can print that stack trace to find out, from where a particular method is get called in execution flow.

One of the easiest way of printing stack trace of current thread in Java is by using dumpStack()  method from java.lang.Thread class. This method prints stack trace of thread on which it get's called. You can use Thread.currentThread() method to get reference of current thread before calling this method

Another way printing stack trace is using printStackTrace() method of Throwable class

Main difference between using dumpStack() and printStackTrace() is first entry in Stack, In case of dumpStack() first entry is always java.lang.Thread.dumpStack(), while in later case it's the method from where you printed stack trace. If you don't want to print stack trace and rather wants it in Java program, you can use getStackTrace() method from Thread class. This method returns an array of StackTraceElement.

public class StackTraceExample {

 public static void main(String args[]) 
   { 
  //calling a method to print stack trace further down
  first(); 
 } 
 public static void first()
 { 
  second();
  } 
 
 private static void second() 
 { 
  third();
 }
 
 private static void third() 
 { 
  //If you want to print stack trace on console than use dumpStack() method 
  System.err.println("Stack trace of current thread using dumpStack() method"); 
  Thread.currentThread().dumpStack(); 
  
  //This is another way to print stack trace from current method 
  System.err.println("Printing stack trace using printStackTrace() method of Throwable "); 
  new Throwable().printStackTrace(); 
  
  //If you want stack trace as StackTraceElement in program itself than //use getStackTrace() method of Thread class 
  StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); 
  
  //Once you get StackTraceElement you can also print it to console 
  System.err.println("displaying Stack trace from StackTraceElement in Java"); 
  for(StackTraceElement st : stackTrace)
  {
   System.err.println(st);
  }

  }
}


Output:
Stack trace of current thread using dumpStack() method
java.lang.Exception: Stack trace
 at java.lang.Thread.dumpStack(Thread.java:1206)
 at StackTraceExample.third(StackTraceExample.java:22)
 at StackTraceExample.second(StackTraceExample.java:15)
 at StackTraceExample.first(StackTraceExample.java:10)
 at StackTraceExample.main(StackTraceExample.java:6)
Printing stack trace using printStackTrace() method of Throwable 
java.lang.Throwable
 at StackTraceExample.third(StackTraceExample.java:26)
 at StackTraceExample.second(StackTraceExample.java:15)
 at StackTraceExample.first(StackTraceExample.java:10)
 at StackTraceExample.main(StackTraceExample.java:6)
displaying Stack trace from StackTraceElement in Java
java.lang.Thread.getStackTrace(Thread.java:1436)
StackTraceExample.third(StackTraceExample.java:29)
StackTraceExample.second(StackTraceExample.java:15)
StackTraceExample.first(StackTraceExample.java:10)
StackTraceExample.main(StackTraceExample.java:6)

Read More...

Tuesday, 2 April 2013

How Synchronization works in Java ?

Leave a Comment

Synchronization
Synchronization in Java is an important concept since Java is a multi-threaded language where multiple threads run in parallel to complete program execution. In multi-threaded environment synchronization of java object or synchronization of java class becomes extremely important. Synchronization in Java is possible by using java keyword "synchronized" and "volatile”. Concurrent access of shared objects in Java introduces to kind of errors: thread interference and memory consistency errors and to avoid these errors you need to properly synchronize your java object to allow mutual exclusive access of critical section to two threads.

Why in Java
If your code is executing in multi-threaded environment you need synchronization for objects which are shared among multiple threads to avoid any corruption of state or any kind of unexpected behavior. Synchronization in Java will only be needed if shared object is mutable. if your shared object is read only or immutable object you don't need synchronization despite running multiple threads. Same is true with what threads are doing with object if all the threads are only reading value then you don't require synchronization in java. JVM guarantees that Java synchronized code will only be executed by one thread at a time.
  • synchronized keyword in java provides locking which ensures mutual exclusive access of shared resource and prevent data race.
  • synchronized keyword involve locking and unlocking. before entering into synchronized method or block thread needs to acquire the lock at this point it reads data from main memory than cache and when it release the lock it flushes write operation into main memory which eliminates memory inconsistency errors.
  • You can have both static synchronized method and non static synchronized method and synchronized blocks in java but we can not have synchronized variable in java.
  • Block synchronization in java is preferred over method synchronization in java because by using block synchronization you only need to lock the critical section of code instead of whole method. Since java synchronization comes with cost of performance we need to synchronize only part of code which absolutely needs to be synchronized.

    Example of synchronized method in Java


    Using synchronized keyword along with method is easy just apply synchronized keyword in front of method. What we need to take care is that static synchronized method locked on class object lock and non static synchronized method locks on current object (this). So it’s possible that both static and non static java synchronized method running in parallel.  This is the common mistake a naive developer do while writing java synchronized code.


public class Counter{
private static int count = 0;

public static synchronized int getCount(){
  return count;
}

public synchoronized setCount(int count){
   this.count = count;
}

}


In this example of java synchronization code is not properly synchronized because both getCount() and setCount() are not getting locked on same object and can run in parallel which results in getting incorrect count. Here getCount() will lock in Counter.class object while setCount() will lock on current object (this). To make this code properly synchronized in java you need to either make bothmethod static or non static or use java synchronized block instead of java synchronized method.
Example of synchronized block in Java



public class Singleton{
private static volatile Singleton _instance;

public static Singleton getInstance(){

   if(_instance == null){
            synchronized(Singleton.class){
              if(_instance == null)
              _instance = new Singleton();
            }

   }
   return _instance;

}




This is a classic example of double checked locking in Singleton. In this example of java synchronized code we have made only critical section (part of code which is creating instance of singleton) synchronized and saved some performance because if you make whole method synchronized every call of this method will be blocked while you only need to create instance on first call.

Important points of synchronized keyword in Java

  1. Synchronized keyword in Java is used to provide mutual exclusive access of a shared resource with multiple threads in Java. Synchronization in java guarantees that no two threads can execute a synchronized method which requires same lock simultaneously or concurrently.
  2. You can use java synchronized keyword only on synchronized method or synchronized block.
  3. When ever a thread enters into java synchronized method or block it acquires a lock and whenever it leaves java synchronized method or block it releases the lock. Lock is released even if thread leaves synchronized method after completion or due to any Error or Exception.
  4. Java Thread acquires an object level lock when it enters into an instance synchronized java method and acquires a class level lock when it enters into static synchronized java method.
  5. java synchronized keyword is re-entrant in nature it means if a java synchronized method calls another synchronized method which requires same lock then current thread which is holding lock can enter into that method without acquiring lock.
  6. Java Synchronization will throw NullPointerException if object used in java synchronized block is null e.g. synchronized (myInstance) will throws NullPointerException if myInstance is null.
  7. One Major disadvantage of java synchronized keyword is that it doesn't allow concurrent read which you can implement using java.util.concurrent.locks.ReentrantLock.
  8. One limitation of java synchronized keyword is that it can only be used to control access of shared object within the same JVM. If you have more than one JVM and need to synchronized access to a shared file system or database, the java synchronized keyword is not at all sufficient. You need to implement a kind of global lock for that.
  9. Java synchronized keyword incurs performance cost. Synchronized method in Java is very slow and can degrade performance. So use synchronization in java when it absolutely requires and consider using java synchronized block for synchronizing critical section only.
  10. Its possible that both static synchronized and non static synchronized method can run simultaneously or concurrently because they lock on different object.
  11. Java synchronized code could result in deadlock or starvation while accessing by multiple thread if synchronization is not implemented correctly.
  12. You cannot apply java synchronized keyword with variables and can not use java volatile keyword with method.
  13. java synchronized keyword also synchronizes memory. In fact java synchronized synchronizes the whole of thread memory with main memory.
  14. Do not synchronize on non final field on synchronized block in Java. because reference of non final field may change any time and then different thread might synchronizing on different objects i.e. no synchronization at all. example of synchronizing on non final field :
    private String lock = new String("lock");
synchronized(lock){
System.out.println("locking on :"  + lock);
}

16. Its not recommended to use String object as lock in java synchronized block because string is immutable object and literal string and interned string gets stored in String pool. so by any chance if any other part of code or any third party library used same String as there lock then they both will be locked on same object despite being completely unrelated which could result in unexpected behavior and bad performance. instead of String object its advised to use new Object() for Synchronization in Java on synchronized block.
private static final String LOCK = "lock";   //not recommended
private static final Object OBJ_LOCK = new Object(); //better

public void process() {
   synchronized(LOCK) {
      ........
   }
}
Read More...

Why wait, notify and notifyAll is defined in Object Class and not on Thread

Leave a Comment

1) Wait and notify is not just normal methods or synchronization utility, more than that they are communication mechanism between two threads in Java. And Object class is correct place to make them available for every object if this mechanism is not available via any java keyword like synchronized. Remember synchronized and wait notify are two different area and don’t confuse that they are same or related. Synchronized is to provide mutual exclusion and ensuring thread safety of Java class like race condition while wait and notify are communication mechanism between two thread.

2 ) Locks are made available on per Object basis, which is another reason wait and notify is declared in Object class rather then Thread class.

3) In Java in order to enter critical section of code, Threads needs lock and they wait for lock, they don't know which threads holds lock instead they just know the lock is hold by some thread and they should wait for lock instead of knowing which thread is inside the synchronized block and asking them to release lock. this analogy fits with wait and notify being on object class rather than thread in Java.

Read More...

Difference between Wait and Sleep in Java

Leave a Comment



  1. Main difference between wait and sleep is that wait() method release the acquired lock when thread is waiting while Thread.sleep() method keeps the lock or monitor even if thread is waiting.
  2. wait method in java should be called from synchronized method or block while there is no such requirement for sleep() method.
  3. Thread.sleep() method is a static method and applies on current thread, while wait() is an instance specific method and only got wake up if some other thread calls notify method on same object.
  4. in case of sleep, sleeping thread immediately goes to Runnable state after waking up while in case of wait, waiting thread first acquires the lock and then goes into Runnable state.
  5. wait is called on Object while sleep is called on Thread.
  6. wait is called from synchronized context only while sleep can be called without synchronized block.
  7. Thread.sleep() method is a static method and always puts current thread on sleep.
So based upon your need if you require a specified second of pause use sleep() method or if you want to implement inter-thread communication use wait method.

/*
 * Example of Thread Sleep method in Java
 */
public class SleepTest {
      
       public static void main(String... args){
              System.out.println(Thread.currentThread().getName() + " is going to sleep for 1 Second");
              try {
                     Thread.currentThread().sleep(1000);
              } catch (InterruptedException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
              System.out.println("Main Thread is woken now");
       }

}

Output:
main is going to sleep for 1 Second
Main Thread is woken now

wait example
package defaultt;

public class Customer {
int amount=0;
int flag=0;
public synchronized int withdraw(int amount){
 System.out.println(Thread.currentThread().getName()+" is going to withdraw");
 
       if(flag==0){
        try{
  System.out.println("waiting....");
  wait();
 }catch(Exception e){}
 }
       
 this.amount-=amount;
 System.out.println("withdraw completed");
 return amount;
}

public synchronized void deposit(int amount){
 System.out.println(Thread.currentThread().getName()+" is going to  deposit");
 this.amount+=amount;
 
 notifyAll();
 System.out.println("deposit completed");
        flag=1;
 }


}


package defaultt;

public class Test{
public static void main(String[] args) {
 final Customer c=new Customer();
 
 Thread t1=new Thread(){
  public void run(){
   c.withdraw(5000);
   System.out.println("After withdraw amount is"+c.amount);
  }
 };
 
 Thread t2=new Thread(){
  public void run(){
   c.deposit(9000);
   System.out.println("After deposit amount is "+c.amount);
  }
 };
 
 
 t1.start();
 t2.start();
 
 
}
}

Output:
Thread-0 is going to withdraw
waiting....
Thread-1 is going to  deposit
deposit completed
withdraw completed
After deposit amount is 4000
After withdraw amount is4000
Read More...

Monday, 25 February 2013

What is a race condition?

Leave a Comment

A race condition occurs when 2 or more threads are able to access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any point, you don't know the order at which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are 'racing' to access/change the data.
Often problems occur when one thread does a "check-then-act" (e.g. "check" if the value is X, and then "act" to do something that depends on the value being X) and another thread does something to the value in between the "check" and the "act".
if(x == 5) //The 'Check'
{
   y = x * 2; //The 'Act'
  //If x is changed by another thread in between the if(x==5) and the "y=x*5", y will not be equal to 10.
}
The point being, y could be 10, or it could be anything, depending on whether another thread changed x in between the check and act. You have no real way of knowing.
In order to prevent race conditions occuring, typically you would put a lock around the shared data to ensure that only one thread can access the data at a time. This would mean something like this:
//Obtain lock for x
if(x == 5)
{
   y = x * 2; //Now, nothing can change x until the lock is released. Therefore y = 10
}
//release lock for x
Read More...

Monday, 10 December 2012

Thread safe in java

Leave a Comment

Thread safe simply means that it may be used from multiple threads at the same time without causing problems. This can mean that access to any resources are synchronized, or whatever.
Consider the following method:
private int myInt = 0;
public int AddOne()
{
    int tmp = myInt;
    tmp = tmp + 1;
    myInt = tmp;
    return tmp;
}
Now thread A and thread B both would like to execute AddOne(). but A starts first and reads the value of myInt (0) into tmp. Now for some reason the scheduler decides to halt thread A and defer execution to thread B. Thread B now also reads the value of myInt (still 0) into it's own variable tmp. Thread B finishes the entire method, so in the end myInt = 1. And 1 is returned. Now it's Thread A's turn again. Thread A continues. And adds 1 to tmp (tmp was 0 for thread A). And then saves this value in myInt. myInt is again 1.
So in this case the method AddOne was called two times, but because the method was not implemented in a thread safe way the value of myInt is not 2, as expected, but 1 because the second thread read the variable myInt before the first thread finished updating it.
Creating thread safe methods is very hard in non trivial cases. And there are quite a few techniques. In Java you can mark a method as synchronized, this means that only one thread can execute that method at a given time. The other threads wait in line. This makes a method thread safe, but if there is a lot of work to be done in a method, then this wastes a lot of space. Another technique is to 'mark only a small part of a method as synchronized' by creating a lock or semaphore, and locking this small part (usually called the critical section). There are even some methods that are implemented as lockless thread safe, which means that they are built in such a way that multiple threads can race through them at the same time without ever causing problems, this can be the case when a method only executes one atomic call. Atomic calls are calls that can't be interrupted and can only be done by one thread at a time.
Read More...