10 Guidelines to thread safe code, most important point we must take care of in multithreading programs


In multithreading environment it’s important very important to write thread safe, thread unsafe code can cause a major threat to your application. I have posted many articles regarding thread safety. So overall this article will be revision of what we have learned so far i.e. writing thread safe healthy code and avoiding any kind of deadlocks.

  1. If method is exposed in multithreading environment and it’s not synchronized (thread unsafe) than it might lead us to race condition, we must try to use synchronized block and synchronized methods. Multiple threads may exist on same object but only one thread of that object can enter synchronized method at a time, though  threads on different object can enter same method at same time.

  1. Even static variables are not thread safe, they are used in static methods and if static methods are not synchronized then thread on same or different object can enter method concurrently. Multiple threads may exist on same or different objects of class but only one thread can enter static synchronized method at a time, we must consider making static methods as synchronized.

  1. If possible, try to use volatile variables. If a field is declared volatile all threads see a consistent value for the variable. Volatile variables at times can be used as alternate to synchronized methods as well.

  1. Final variables are thread safe because once assigned some reference of object they cannot point to reference of other object.

s is pointing to String object.
 public class MyClass {
final String s=new String("a");
   void method(){
          s="b"; //compilation error, s cannot point to new reference.
   }
 }


If final is holding some primitive value it cannot point to other value.

 public class MyClass {
final int i=0;
   void method(){
          i=0;  //compilation error, i cannot point to new value.
   }
 }


  1. Usage of local variables : If possible try to use local variables, local variables are thread safe, because every thread has its own stack, i.e. every thread has its own local variables and its pushes all the local variables on stack.
 public class MyClass {
   void method(){
    int i=0; //Local variable, is thread safe.
   }
 }


  1. We must avoid using  deadlock prone deprecated thread methods such as destroy(), stop(), suspend() and resume().

  1. Using thread safe collections : Rather than using ArrayList we must Vector and in place of using HashMap we must use ConcurrentHashMap or HashTable.

  1. We must use VisualVM  or jstack  to detect problems such as deadlocks and time taken by threads to complete in multi threading programs.

  1. Using ThreadLocal : ThreadLocal is a class which provides thread-local variables. Every thread has its own ThreadLocal value that makes ThreadLocal value threadsafe as well.

  1. Rather than StringBuffer try using immutable classes such as String. Any change to String produces new String.

/** JavaMadeSoEasy.com */



RELATED LINKS>

Race Condition >

Race condition in multithreading and it's solution




DeadLock and it’s detection >

Deadlock in multithreading - program to form DeadLock, solving DeadLock, measures to avoid Deadlock.


VisualVM - Thread dumps - Generating and analyzing Thread Dumps using VisualVM - step by step detail to setup VisualVM with screenshots


JSTACK - Thread dumps - Generating and analyzing Thread Dumps using JSATCK - step by step detail to setup JSTACK with screenshots


Reason why suspend() and resume() methods are deprecated and Deadlock prone

destroy() method in java - usage, reason why destroy() method is deprecated and Deadlock prone.



Object and class lock >

Acquiring object lock - synchronization blocks and methods- multiple threads may exist on same object but only one thread of that object can enter synchronized block/method at a time.
Acquiring lock on class, 2 Ways to acquire lock on class

Difference between object Lock and class Lock



Thread Pool, Thread local, Busy Spin >

Implement Thread pool in java

ThreadLocal in multithreading in java - methods and usage with program

Busy Spin - What is busy spin? Consumer Producer problem with busy spin and solution to busy spin.


Interviews >

THREADS - Top 80 interview questions and answers (detailed explanation with programs), includes important MultiThreading OUTPUT questions






eEdit
Must read for you :