Thursday 19 June 2014

Multithreading



What is the difference between processes and threads?
A process is an execution of a program but a thread is a single execution sequence within the process.
A process can contain multiple threads. A thread is sometimes called a lightweight process.

Threads can be created by either
·                     Extending the Thread class.
·                     Implementing the Runnable interface.
·                     Using the Executor framework (this creates a thread pool) 
 
The state chart diagram below describes the thread states.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiykSC2W9TNQ6ZKtBU3foJXBBF-icJBEAq_UuR7FunpAbktcBpi-XWIwJui3FKGC8hW3IR-b7OaSioENw8Fs6khjkBKXoaqhhw3bekvz2siW_jZpvdBqvV_fypbwLeNSlGh45DsPvrFnDYu/s1600/thread_states.JPG
Sleeping – a.k.a. Timed-waiting state

Java Thread

The wait( ), notify (), and notifyAll( ) methods are used to provide an efficient way for threads to communicate with each other. These are called only in synchronized block.
·         Calling wait causes the current thread to wait to acquire the lock of the Object, and
·         calling notify/notifyAll relinquishes the lock and notify the threads waiting for that lock.
·         Thread.yeild() - Causes the currently executing thread object to temporarily pause and allow other threads to execute.
·         t.join( ) allows the current thread to wait indefinitely until thread “t” is finished
t.join (5000) allows the current thread to wait for thread “t” to finish but does not wait longer than 5 seconds.
sleep() – Keep the current thread into sleep hence this is in Thread class, whereas wait( ), notify (), and notifyAll( ) are in Object class because it has to communicate between the threads.

sleep():
               It is a static method on Thread class. It makes the current thread into the
               "Not Runnable" state for specified amount of time. During this time, the thread
               keeps the lock (monitors) it has acquired.
              
wait():
               It is a method on Object class. It makes the current thread into the "Not Runnable"
               state. Wait is called on a object, not a thread. Before calling wait() method, the
               object should be synchronized, means the object should be inside synchronized block.
               The call to wait() releases the acquired lock.


Q: Why thread communication methods wait(), notify() and notifyAll() are in Object class?
 In Java every Object has a monitor and wait, notify methods are used to wait for the Object monitor or to notify other threads that Object monitor is free now. There is no monitor on threads in java and synchronization can be used with any Object, that’s why it’s part of Object class so that every class in java has these essential methods for inter thread communication.

Q: Why Thread sleep() and yield() methods are static?
Thread sleep() and yield() methods work on the currently executing thread. So there is no point in invoking these methods on some other threads that are in wait state. That’s why these methods are made static so that when this method is called statically, it works on the current executing thread and avoid confusion to the programmers who might think that they can invoke these methods on some non-running threads.

Q:How can we achieve thread safety in Java?
There are several ways to achieve thread safety in java – synchronization, atomic concurrent classes, implementing concurrent Lock interface, using volatile keyword, using immutable classes and Thread safe classes. Learn more at thread safety tutorial.

Q:What is Java Thread Dump, How can we get Java Thread dump of a Program?
Thread dump is list of all the threads active in the JVM, thread dumps are very helpful in analyzing bottlenecks in the application and analyzing deadlock situations. There are many ways using which we can generate Thread dump – Using Profiler, Kill -3 command, jstack tool etc.
Read this post to know more about generating thread dump in java.

Q:What is BlockingQueue? How can we implement Producer-Consumer problem using Blocking Queue?
java.util.concurrent.BlockingQueue is a Queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.
BlockingQueue doesn’t accept null values and throw NullPointerException if you try to store null value in the queue.
BlockingQueue implementations are thread-safe. All queuing methods are atomic in nature and use internal locks or other forms of concurrency control.

ConcurrentHashMap is the class that is similar to HashMap but works fine when you try to modify your map at runtime.


Callable is similar to Runnable interface but it can return any Object and able to throw Exception.
Using Future we can find out the status of the Callable task and get the returned Object. It provides get() method that can wait for the Callable to finish and then return the result.
Check this post for Callable Future Example.

Disadvantage of Synchronization:
·         can cause deadlocks when two threads are waiting on each other to do something
·         synchronized code has the overhead of acquiring lock, which can adversely affect the performance.

volatile variable is one whose value is always written to and read from "main memory". That means that different threads can access the variable.
As of Java 5, accessing a volatile variable creates a memory barrier: it effectively synchronizes all cached copies of variables with main memory, just as entering or exiting a synchronized block that synchronizes on a given object.

Thread Scheduler is the Operating System service that allocates the CPU time to the available runnable threads.
Time Slicing is the process to divide the available CPU time to the available runnable threads.
Context Switching is the process of storing and restoring of CPU state so that Thread execution can be resumed from the same point at a later point of time. 



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.

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

JVM parameters in Java   - JVM option it can be divided into two parts:

1)    JVM Options that begin with -X are non-standard (thy are not guaranteed to be supported on all JVM implementations), and are subject to change without notice in subsequent releases of the JDK.
2)    JVM Options or parameters which are specified with -XX are not stable and are not recommended for casual use. These options are subject to change without notice also.

Frequently used JVM parameters for heap, GC and debugging

Stack size -> -Xss
Heap size -> -Xms[starting size] –Xmx[maximum size]

Q. What is a ThreadLocal class?  
A. ThreadLocal is a handy class for simplifying development of 
thread-safe concurrent programs by making the object stored in this class not sharable between threads.
ThreadLocal class encapsulates non-thread-safe classes to be safely used in a multi-threaded environment and also allows you to create per-thread-singleton. 

References:


No comments:

Post a Comment