Thread safety in java is the process to make our program safe to use in multi threaded environment, there are different ways through which we can make our program thread safe.
1) Synchronization is the easiest and most widely used tool for thread safety in java.
2) Immutable objects are by default thread safe because there state can not be modified once created. For example, String class is immutable in java which inherently thread-safe.
3) Use of Atomic Wrapper classes from java.util.concurrent.atomic package. Atomic operations in Java are thread-safe. For example AtomicInteger.
4) Use of locks from java.util.concurrent.locks package.
5) Using volatile keyword with variables to make every thread read the data from memory, not read from thread cache.
6) Using thread safe classes for thread safety. Example of thread-safe class in Java: Vector, Hashtable, ConcurrentHashMap, String etc.
7) Locking is one way of achieving thread-safety in Java.
No comments:
Post a Comment