Friday, February 19, 2010

Thread

1. What is a thread?

A thread is an independent path of execution within a process. Many threads can run concurrently within a process. A process is a program having its own address space.

----------------------------------------------------------------------

2. What is the difference between multithreading & multitasking?

In multithreaded program, more than one thread is running concurrently. It is not equivalent to starting a program twice at the same time. If we start two or more programs at a time, this will require separate address space for both data and code, making it more CPU intensive operation. This type of program execution is called multitasking.

In multithreaded environment, sharing of data is done across the threads, which makes it less CPU intensive but brings up some other issues which may even corrupt data if not handled carefully.

Multitasking is a heavyweight task that require own address space. Communication between different processes is very expensive. Also context switching from one process to another is costly since they are running in different address spaces.

Multithreading is lightweight. Communication between two threads is not that expensive as it is in case of processes. Context switching is also less expensive as both share same address space.

----------------------------------------------------------------------

3. What is synchronization?

You can think of a single threaded program which is accessing some resource at a time. You are not worried by the fact that if some other thread is accessing same resource at the same time.

With multithreaded environment there will be possibility that two or more threads are trying to access same resource at the same time. This may lead to some error. Colliding over resource must be prevented to avoid any such error.

Consider the bathroom in your house; multiple people (threads) may each want to have exclusive use of the bathroom (the shared resource). To access the bathroom, a person knocks on the door to see if it's available. If so, they enter and lock the door. Any other thread that wants to use the bathroom is "blocked" from using it, so that thread waits at the door until the bathroom is available.

In Java, to solve this problem of thread collision, all the multithreaded program should serialize access to shared resource. This is achieved by putting a locked clause around a piece of shared code so that one thread at a time may pass through that piece of code. Serializing access of shared resource is called synchronization. Synchronization is Java is achieved by "synchronized" keyword.

----------------------------------------------------------------------