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.
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:
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.
Read only or final variables in Java are also thread-safe in Java.
Locking is one way of achieving thread-safety in Java.
Static variables if not synchronized properly becomes major cause of thread-safety issues.
Example of thread-safe class in Java: Vector, Hashtable, ConcurrentHashMap, String etc.
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.
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.
In order to avoid thread-safety issue minimize sharing of objects between multiple thread. 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.