thread-safety or thread-safe code in Java refers to code which can safely be used or shared in concurrent or multi-threading environment and they will behave as expected. any code, class or object which can behave differently from its contract on concurrent environment is not thread-safe. thread-safety is one of the risk introduced by using threads in Java and I have seen java programmers and developers struggling to write thread-safe code or just understanding what is thread-safe code and what is not? This will not be very detailed article on thread-safety or low level details of synchronization in Java instead we will keep it simple and focus on one example of non thread-safe code and try to understand what is thread-safety and how to make an code thread-safe.
How to make Thread-Safe Code in Java
Example of Non Thread Safe Code in Java
Here is an example of non thread-safe code, look at the code and find out why this code is not thread safe ?
/*
* Non Thread-Safe Class in Java
*/
public class Counter {
private int count;
/*
* This method is not thread-safe because ++ is not an atomic operation
*/
public int getCount(){
return count++;
}
}
Above example is not thread-safe because ++ (increment operator) is not an atomic operation and can be broken down into read, update and write operation. if multiple thread call getCount() approximately same time each of these three operation may coincide or overlap with each other for example while thread 1 is updating value , thread 2 reads and still gets old value, which eventually let thread 2 override thread 1 increment and one count is lost because multiple thread called it concurrently.
How to make code Thread-Safe in Java
There are multiple ways to make this code thread safe in Java:
1) Use synchronized keyword in Java and lock the getCount() method so that only one thread can execute it at a time which removes possibility of coinciding or interleaving.
2) use Atomic Integer, which makes this ++ operation atomic and since atomic operations are thread-safe and saves cost of external synchronization.
here is a thread-safe version of Counter class in Java:
/*
* Thread-Safe Example in Java
*/
public class Counter {
private int count;
AtomicInteger atomicCount = new AtomicInteger( 0 );
/*
* This method thread-safe now because of locking and synchornization
*/
public synchronized int getCount(){
return count++;
}
/*
* This method is thread-safe because count is incremented atomically
*/
public int getCountAtomically(){
return atomicCount.incrementAndGet();
}
}
Important points about Thread-Safety in Java
Here is some points worth remembering to write thread safe code in Java, these knowledge also helps you to avoid some serious concurrency issues in Java like race condition or deadlock in Java:
1) Immutable objects are by default thread-safe because there state can not be modified once created. Since String is immutable in Java, its inherently thread-safe.
2) Read only or final variables in Java are also thread-safe in Java.
3) Locking is one way of achieving thread-safety in Java.
5) Example of thread-safe class in Java: Vector, Hashtable, ConcurrentHashMap, String etc.
6) Atomic operations in Java are thread-safe e.g. reading a 32 bit int from memory because its an atomic operation it can't interleave with other thread.
7) local variables are also thread-safe because each thread has there own copy and using local variables is good way to writing thread-safe code in Java.
8) In order to avoid thread-safety issue minimize sharing of objects between multiple thread.
9) Volatile keyword in Java can also be used to instruct thread not to cache variables and read from main memory and can also instruct JVM not to reorder or optimize code from threading perspective.
That’s all on how to write thread safe class or code in Java and avoid serious concurrency issues in Java. To be frank thread-safety is a little tricky concept to grasp, you need to think concurrently in order to catch whether a code is thread-safe or not. Also JVM plays a spoiler since it can reorder code for optimization, so the code which looks sequential and runs fine in development environment not guaranteed to run similarly in production environment because JVM may ergonomically adjust itself as server JVM and perform more optimization and reorder which cause thread-safety issues.
Thanks
Related Java Tutorials
Tidak ada komentar:
Posting Komentar