Sunday, March 10, 2013

Java Threads and Locks



Thread - a light weighted set of instructions that forms the execution logic of an algorithm.
Java has few types of Threads managed by JVM process
    - Application Threads
    - JVM internal threads (GC threads, code generation and code optimizer threads, Finalizer threads)

And, each Java thread has its own Stack space (which can also be set to a specific value using -Xss)

One more interesting thing is 'locks'. When threads share a resource, the resource must be controlled by using the 'synchronized' or wait, notify keywords. The synchronization happens with the use of 'locks'. Each thread must hold a lock on an object it is working.

There are four different kinds of locks:
Fat locks: A fat lock is a lock with a history of contention (several threads trying to take the lock simultaneously), or a lock that has been waited on (for notification).
Thin locks: A thin lock is a lock that does not have any contention.
Recursive locks: A recursive lock is a lock that has been taken by a thread several times without having been released.
Lazy locks: A lazy lock is a lock that is not released when a critical section is exited. Once a lazy lock is acquired by a thread, other threads that try to acquire the lock have to ensure that the lock is, or can be, released. Lazy locks are used by default in Oracle JRockit JVM 27.6. In older releases, lazy locks are only used if you have started the JVM with the -XXlazyUnlocking option.

Threads while in the process of acquiring locks, goes in to two states - Spinning and Sleeping. Spinning is a state where the thread continuously checks on a lock whether it is released or not. While Sleeping is a state where the thread passively checks for a lock is released or not. The first state eats up CPU while seconds state yields CPU to other threads.

Now, we have seen Threads and the Locks, lets see one more interesting thing - Lock Chains!

Threads forms lock chains if they are queuing up to obtain a lock while the head is holding the lock for its actions. If there are long lock chains then the applications threads are spending long times in waiting mode there by resulting in long latencies.

And, there are three types of lock chains - Open, Deadlocked, Blocked.

Open is a simple lock chain where the head thread is holding a lock which is needed for the threads that are in the chain.
Deadlock chain is two threads waiting on each other. As it is a circular wait, there is no head in this lock chain.
Blocked chain is an extension hanging from any of the above two cases. Any more threads waiting on a thread which is either in an open chain or in a deadlock chain.






No comments:

Post a Comment