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.

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.

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.

publicclass 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.

publicclass MyClass {

finalinti=0;

void method(){

i=0; //compilation error, i cannot point to new value.

}

}

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.