Java Thread Safety
1 Thread safety is the process to make our program safe to use in multithreaded
environment, there are different ways through which we can make our program
thread safe.
2 Synchronization is the easiest and most widely used tool for thread safety in
java.
3 Use of Atomic Wrapper classes from java.util.concurrent.atomic package. For
example AtomicInteger
4 Use of locks from java.util.concurrent.locks package.
5 Using thread safe collection classes, check this post for usage of
ConcurrentHashMap for thread safety.
6 Using volatile keyword with variables to make every thread read the data from
memory, not read from thread cache.
7 Adding synchronized to this method will makes it thread-safe. When
synchronized is added to a static method, the Class object is the object which
is locked.
class MyCounter {
private static int counter = 0;
public static synchronized int getCount() {
return counter++;
}
}
Read More →