Skip to content

Java Threads#

Thread Safety In Java#

  • Thread safety in java is the process to make our program safe to use in multi threads environment, there are different ways through which we can make our program thread safe.
  • Synchonization is the easiest and most widely used tool for thread safety in java. JVM guarantees that synchronized code will be executed by only on thread at a time. Java keyword synchronized is used to create synchronized code and internally it uses locks on object or class to make sure only one thread is executing the synchronized code.
  • Using Atomic Wrapper Classes from java.util.concurrent.atomic package Ex: AtomicInterger
  • Using locks from java.util.concurrent.locks package
  • Using thread safe collection classes, ex: Hashtable
  • Using volitile keyword with variable to make every thread read the data from memory, not read from thread cache.

Java ThreadLocal#

  • ThreadLocal in java is another way to achieve thread-safety apart from writing immutable classes. Thread local can be considered as a scope of access like session scope or request scope. In threadlocal, you can set any object and this object will be local and global to the specific thread which is accessing this object.
  • Java ThreadLocal class provides thread-local variables. It enables you to create variables that can only be read and write by the same thread. If two threads are executing the same code and that code has a referece to a thread ThreadLocal variable then the two threads can not see the local variable of each other.

Java ThreadPool#

  • Java ThreadPool represents a group of worker threads that are waiting for the job and reuse many times. In case of thread pool, a group of fixed size thread pool is pulled out and assigned a job by the service provider. After completion of the job, thread is contained in the thread pool again.
  • Advantages of java thread pool:
  • Better performance: It saves time because there is no need to create new thread.
  • Thread pool is used in Servlet and JSP where container creates a thread pool to process the request.  #zoom
  • We will continue to discuss about thread pool in Spring @Async annotation.

See Also#