Showing posts with label Multithreading. Show all posts
Showing posts with label Multithreading. Show all posts

Thursday, February 18, 2010

What is Multithreading?


If two or more threads can run through your program concurrently, then that is known as multi threading:
  • Advantages : Multithreading can make the execution faster by making use of the unused resources by one thread at some point of time.
  • Disadvantages : Concurrent execution of multiple threads can lead to delay in the completion of individual thread due to sharing of resources.
Improper use of multithreading can lead to corrupted data. To avoid this, we can use synchronization. Synchronization is used to ensure that only one thread executes in a critical region at a time. Critical Regions are places where modification in the data is done. Ideally, only one thread should be executing in the critical regions.
Synchronization can be achieved by two ways:
  • Synchronized blocks:  We use synchronized blocks when we intend only a few lines of code to be synchronized.
class myClass {
    myMethod() {
      synchronized (object) {
         statement block
      }
   }
}
In this case, the object specified in the statement is the lock.
  • Synchronized methods : We use synchronized methods when we want the complete method to be synchronized.
class myClass {
   synchronized type myMethod() {
      statement block
   }
}
In this case, lock is obtained on the object being referenced in the synchronized method. Two synchronized methods referring to the same object can not be called simultaneously from two different threads.

Deadlock :  When two or more threads are waiting for each other to release some resource, they are unable to proceed with their own executions and keep on waiting. This condition is known as deadlock.
Deadlock can also include more than two threads. This happens when more than two thread are waiting for another thread to release the lock over a resource. See an example below:
Thread 1 waits for Resource A locked by Thread 2
Thread 2 waits for Resource B locked by Thread 3
Thread 3 waits for Resource C locked by Thread 1