Showing posts with label MultiThreading. Show all posts
Showing posts with label MultiThreading. Show all posts

Friday, October 22, 2010

How to generate a threaddump for java based process

Windows
Can be captured in following ways

1) Using Ctrl-Break :
The Java application that you want to produce a thread dump for must be running / started in a command console. When you want to produce a thread dump press Ctrl-Break.

2) Using jstack :
step 1) Use jps command to find out the process id (pid) of the java process for which the thread dump is to be generated.
eg output for jps
C:\>jps
3316 Deadlock
3476 Jps
step 2) Use jstack command to along with the process id to generate the threaddump.
syntax : jstack
eg: c:/>jstack 3316

Linux or Solaris

1)Using Ctrl-\:
If the JVM is running in a console then simply press Ctrl-\.

2)Sending QUIT signal:
If the JVM is running in the background then send it the QUIT signal:

kill -QUIT process_id

There process_id is the process number of the running Java process. The thread dump will be sent to wherever standard out is redirected too.

You can generally get the process numbers of of all running Java processes with the command:

ps axf | grep java

3) Using jstack:
Steps as mentioned above in the Windows Section

Why Thread Dump is required ?

You need to generate threaddump of java based process whenever...
1) JVM refuses to exit cleanly.This could be due to
           a) Some user defined thread running infintely
           b) Some threads getting deadlock
           c) Some threads going in infinite wait state.
2) Application is unresponsive.
3) Application is not behaving as expected.

Saturday, January 23, 2010

How "thread safe" is your class ?

This post discusses the various thread safety levels for a java classes.
Thread safety of a class is not an
all-or-nothing proposition and is difficult to define.
eg: The methods of Vector are all synchronized, and Vector is clearly designed to function in multithreaded environments. But there are limitations to its thread safety, namely that there are state dependencies between certain pairs of methods. (Similarly, the iterators returned by Vector.iterator() will throw a ConcurrentModificationException if the Vector is modified by another thread during iteration.)

Joshua Bloch has suggested following five levels of thread safety of a class :

Immutable: Instances of the class are constant and cannot be changed. There are, therefore, no thread safety issues.
eg:Integer,String,and BigInteger

Thread-safe: Instances of the class are mutable but they can be used safely in a concurrent environment. All methods provided by the class are properly synchronized either at the interface level or internally within the method.
eg:Timer

Conditionally thread-safe: Instances of the class for which each individual operation may be thread-safe, but certain sequences of operations may require external synchronization.
eg:Hashtable and Vector
Explanation-Iterator returned by Vector class assumes that the underlying collection will not be mutated while the iterator traversal is in progress. To ensure that other threads will not mutate the collection during traversal, the iterating thread should be sure that it has exclusive access to the collection for the entirety of the traversal. Typically, exclusive access is ensured by synchronizing on a lock -- and the class's documentation should specify which lock that is (typically the object's intrinsic monitor)

Thread-compatible: Instances of the class provide no synchronization. However, instances of the class can be safely used in a concurrent environment, if the caller provides the synchronization by surrounding each method (or sequence of method calls) with the appropriate lock.
eg:ArrayList,HashMap,java.text.SimpleDateFormat

Thread-hostile: Instances of the class should not be used in a concurrent environment even if the caller provides external synchronization. Ideally, classes should not be written that are thread-hostile. Typically a thread-hostile class is accessing static data or the external environment.
eg:Class which calls System.setOut().

The developer for a java class should mention the thread safety in terms of one of the levels mentioned above in the Javadoc. This would help the people who would be maintaining the class in future and also the consumers of these classes.

References : Bloch, J. (2001), Effective Java: Programing Language Guide, Addison-Wesley.

Thread-related Exceptions in Java

This post summarizes in one place the thread-related exceptions in Java.



1) IllegalMonitorStateException is thrown when
  • the wait, notify, or notifyAll methods are called by a thread that has not locked the associated object.
2) IllegalThreadStateException is thrown when
  • the start method is called and the thread has already been started.
  • the setDaemon method has been called and the thread has already been started.
  • an attempt is made to destroy a nonempty thread group.
  • an attempt is made to place a thread into a thread group (via the Thread constructor) and the thread group has already been destroyed.
  • an attempt is made to get the exit value of a nonterminated Process.
3) SecurityException is thrown by the security manager when
  • the Thread constructor has been called and it is requested that the thread to be created be placed into a thread group for which it has no security permission.
  • a stop or destroy method has been called on a thread for which the caller does not have the correct permission for the operation requested.
  • the ThreadGroup constructor has been called with a parent group parameter for which the calling group has no permission.
  • a stop or destroy method has been called on a thread group for which the caller does not have the correct permission for the operation requested.
4) NullPointerException is thrown when
  • a null pointer is passed to the stop method.
  • a null pointer is passed to the ThreadGroup constructor for the parent group.
5) InterruptedException is thrown when
  • a thread that has made a join method call is woken up by the thread being interrupted rather than by the target thread terminating.
  • a thread that has made a wait method call is woken up by the thread being interrupted rather than by a notify or notifyAll.
  • a thread that has made a waitFor method call is woken up by the thread being interrupted rather than by the target process terminating.

Friday, January 22, 2010

How to deal with deadlock ?

There are three possible approaches to dealing with deadlock:

  • Deadlock prevention — Deadlock can be prevented by ensuring that at least one of the four conditions required for deadlock never occurs. For example, by using sharable resources, never holding one resource while waiting for another, making resources preemptible, or by imposing a strict logical ordering on resource allocation requests so that all threads request resources in the same order.

  • Deadlock avoidance — If more information on the pattern of resource usage is known, then it is possible to construct an algorithm that will allow all the four conditions necessary for deadlock to occur, but which will also ensure that the system never enters a deadlock state. A deadlock avoidance algorithm will examine dynamically the resource allocation state and take action to ensure that the system can never enter into deadlock. Any resource allocation request that is potentially unsafe is denied.

  • Deadlock detection and recovery — In many general-purpose concurrent systems, the resource allocation usage is a priori unknown. Even if it is known, the cost of deadlock avoidance is often prohibitive. Consequently, many of these systems will ignore the problems of deadlock until they enter a deadlock state. They then take some corrective action (for example, by aborting a concurrent activity and preempting its resources.)

What are the conditions which can cause deadlock

There are four necessary conditions that must exist if deadlock is to occur.The conditions are as follows:

  • Mutual exclusion — only one concurrent activity can use a resource at once (that is, the resource is nonsharable or at least limited in its concurrent access); using locks as an example, mutual exclusion locks as opposed to read/write locks are more likely to cause deadlock.

  • Hold and wait — there must exist concurrent activities that are holding resources while waiting for others resources to be acquired; with locks, concurrent activities must be holding locks while waiting to acquire new locks.

  • No preemption — a resource can only be released voluntarily by a concurrent activity; the locks acquired by a concurrent activity cannot be forcibly taken away from it by another activity.

  • Circular wait — a circular chain of concurrent activities must exist such that each activity holds resources (has locked the objects) that are being requested by the next activity in the chain

Wednesday, January 20, 2010

Common Concurrency Challenges

1) Race Condition
Multiple threads access the same shared data without the appropriate locks on shared data.When this condition occurs, one thread may inadvertently overwrite data used by another thread, leading to both loss of information and data corruption.Minimun requirement for Race Condition to occur is 2 threads and 1 shared data object amongst them.

2) Thread Block
A thread calls a long-running operation while holding a lock thereby preventing the progress of other threads.When this condition occurs, application performance can drop dramatically due to a single bottleneck for all threads.

3) Deadlock
Two or more threads wait for locks in a circular chain such that the locks can never be acquired. When this condition occurs, the entire software system may halt, as none of the threads can either proceed along their current execution paths or exit. Minimum requirement for deadlock to occur is 2 threads and 2 shared data objects amongst these 2 threads.

What is Parallel Computing ?

Parallel Computing is the management of a collection of serial tasks

where:
management refers to the policies by which
(a) tasks are scheduled,
(b) premature terminations are handled,
(c) preemptive support is provided,
(d) communication primitives are enabled/disabled, and
(e) the manner in which resources are obtained and released,

and

serial tasks are classified in terms of either
(a) Coarse grain -- where tasks may not communicate prior to conclusion, or
(b) Fine grain -- where tasks may communicate prior to conclusion.