top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

What do you understand by thread-safety ? Why is it required ?

0 votes
What do you understand by thread-safety ? Why is it required ?
posted Nov 18, 2017 by Gn Guruswamy

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Thread safety in java 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.

  1. Synchronization is the easiest and most widely used tool for thread safety in java.
  2. Use of Atomic Wrapper classes from java.util.concurrent.atomic package. For example AtomicInteger
  3. Use of locks from java.util.concurrent.locks package.
  4. Using thread safe collection classes, check this post for usage of ConcurrentHashMap for thread safety.
  5. Using volatile keyword with variables to make every thread read the data from memory, not read from thread cache.

Thread Safety in Java is a very important topic. Java provide multi-threaded environment support using Java Threads, we know that multiple threads created from same Object share object variables and this can lead to data inconsistency when the threads are used to read and update the shared data.The reason for data inconsistency is because updating any field value is not an atomic process, it requires three steps; first to read the current value, second to do the necessary operations to get the updated value and third to assign the updated value to the field reference.

answer Nov 19, 2017 by Frank Lee
Contact Us
+91 9880187415
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Karnataka INDIA.