MultiThreading and its challenges!
- 0 Comments
In this real world, optimum utilization of resources has always been the prime concern of any organization ,industry and institution; irrespective of the size, fashion and nature of their operations; various techniques and principals are used to achieve this goal.
In Java also, it’s always a prime challenge for a developer to use it’s available resources up to their optimum level. And in Java, this is done through concepts of concurrent programming and two main ingredients of concurrent programming are threads and process.
Process consists of self-execution environment, block of code and consumes it’s own space in memory. While threads, also called light weight process, is termed as separate path of execution in a program .
It’s mandatory for a program in java to have at least one thread to execute. And if there are more than one thread (i.e. multithreaded application), then being the separate path of execution ,all run differently in their own stack without disturbing each other.
So this way, multithreading makes possible the execution of different threads in same program. Multithreading provides many benefits as creation and execution of thread is dead simple and being the light weighted memory consumption is barely an issue.
But every techniques has it’s trade-offs. Same with multithreading it also has it’s own threats and challenges-
As the threads use resources of process, what if one thread tries to suppress others and wants to take control of the same resource already occupied by another thread ?
To control this kind of behavior java, use a methodology called ‘synchronization’ that makes sure that resources are made available to different threads in proper and systematic fashion, and that no thread can take control of resource already occupied by another one .
Unguaranteed behavior:
As threads execute in same program, hence, they share same memory locations. So if a situation occurs when two different threads approach the same location ,what value will be left when both threads finish their job? This behavior is never guaranteed and that’s why outcome of a same program may change when it is run time to time.
Race Condition:
Another problem in multithreading is of race condition – this problem is purely a byproduct of multithreading, never occurs in single thread application. It occurs when multiple threads want to modify the same shared resource.
Deadlock:
A deadlock is a situation where two threads wait for the lock held by each other.
And once this situation occurs, it’s not possible for threads to run again and mostly,
this results in the termination of program.
Testing and data integrity:
Testing a multithreaded application is always a great challenge because outcome never can be guaranteed to be the same every time and, hence, integrity of data always remains in question and that’s why sometime sit becomes essential to use a profiler tool for the testing purpose.
