Tuesday, 5 June 2012

Multithreading is like juggling grenades!

Writing multithreading code is like juggling grenades; when it works it works like a charm, otherwise it's your worst nightmare.

Couple of hours ago I was working on a multithreaded application in Java,  I was immersed in lots of threads and applications. So when you are interacting with say 500 "things" per second and when something goes wrong all the grenades do explode synchronously, that is when you'd catch yourself wishing "Only if Java had shown me a little bit of mercy."

An all time popular question about multithreading is "What are the major problems you expect while implementing multithreading?" Well if someone has read about multithreading their answer would be "I would try to avoid deadlocks" that is when the your average guy screams at the top of his voice and says "You idiot...deadlocks are easy, trying to protect shared data is the most important thing to do" but only the experienced (Saddy) do know that trying to avoid doing nothing is the most important thing.

Still not buying it??? Ok lets start with the inexperienced guy who said to avoid deadlocks. Deadlocks can generally be avoided if you are disciplined. The average guy who might have done some thread coding maybe in Swing, well locking shared variables is not the hardest thing to do. Now coming to Saddy's answer - "Why is doing nothing the worst of things?" When coming to a complex high speed system the first and the second would be the basic requirement without slowing down the system. So you might imagine what's the big deal if a couple of threads waited in the background while waiting for resources. Well if there is one thing experience has taught me is that Threads are always greedy.

Imagine a very large server has - let's say 2000 threads waiting for something to happen...What would happen if Amazon is processing millions of searches daily and half of their server's capacity is spent on waiting for something to happen (WTF), that is money and power going down the drain. The company would need twice the amount of hardware (forgetting the fact that the CFO having a cardiac arrest) for poor thread coding.

Multithreaded coding is a complex task and implementing multithreading in a complex environment is even more complicated. Sometimes a lot of negative answers do lead to a positive solution, remember for a positive: you will always need two negatives. It's not easy and it's not quick and don't mind the project manager; tell him you are waiting for the pi├Ęce de resistance of multithreading.

Then again multithreading is like juggling grenades.

PS: The only guarantee about software development is that the spec always changes.

No comments:

Post a Comment