Common Multi-threading Mistakes in Java - Calling run() instead of start()

Writing multi-threaded and concurrent programs is not easy, not even in Java.  Even senior developers, including myself, make mistakes while writing concurrent Java applications. This is also one of the trickiest area of Java programming language, where misconceptions outnumbers concepts. Considering amount of misconception an average Java programmer has about multi-threading and concurrency, I thought to start a new series about common multi-threading mistakes done by Java programmers; what is better way to learn from common real word mistakes. Learning from mistakes has another name Experience, but if you only learn from your mistakes then there is only limited things you can learn, but if you learn from other peoples mistake, you can learn much more in short span of time.

Have you ever thought, Why writing multi-threaded code is difficult? IMHO, primary reason for this is that it multi-threading makes it hard for a code to speak for itself. Programmer read code sequentially to understand how it's executed, but it is only correct if one and only one thread is executing it. That's why Single-threaded code are easy to read and debug.

As soon as two threads come into the picture, It becomes very difficult to make a prediction about how your code behaves, especially in the absence of any synchronization rules e.g. rules enforced by Java Memory Model. Without JMM you can not make correct predictions about your code in a multi-threaded environment, because it's possible for one thread to stop at an arbitrary point and another thread at different points.

The situation becomes even more tricky if those threads are sharing data between them e.g. in form of objects, a poorly written multi-threaded program can cause deadlock, race condition, and responsiveness issues, which will prevent a Java application to fulfill its promise. I hope, in this series we can learn from each other's mistakes and take a step forward on writing a correct multi-threaded applications in Java.

Multithreading and Concurrency Mistake in Java - Using run() in place of start()

I am starting with one of the simplest examples, this is very common mistakes by junior programmers and caused by half knowledge. They know that anything written in run() method of Runnable interface or Thread class will execute in another thread, but doesn't know how to create another thread in JVM.

Consider the following code :

class KingKong { public static synchronized void main(String[] args) { Thread t = new Thread() { public void run() { kong(); } };; System.out.print("King"); } public static synchronized void kong() { System.out.print("Kong"); } }

What Does It Print?

(a) KingKong

(b) KongKing

(c) It varies

(d) Compile time error

We had this question in our Java written test and you will be surprised by the percentage of answers, whopping 50% answers It varies, 10% says compile-time error, another 15% picks answer a KingKong and rest of 25% chooses KongKing. We also ask to write an explanation of why they choose a particular answer, just to avoid picking someone who is guessing their way.

The 50% developer, who chooses It varies, mentioned that there is no guarantee when a thread will start, so it possible that if themain thread finishes first it will print KongKing and if new thread executes before the main thread.

Wow, what do you say about these developers, seems a decent lot of programmer who knows some part of multi-threading but overlooked critical detail. The next 10% programmer, who chose Compile time error was unsure whether themain method can be synchronized or not and thought that compiler will not like it.

Next 15% says because "King" comes first in code, it will be printed first and "Kong" will be printed later.

Last 25% who chose "KongKing" are the people who got it correct. We were literally disappointed with these numbers because it wasn't such a difficult or a tricky question, but I agree sometimes it's difficult to spot a typo and that's what makes this error very hard to debug.

Why Code Print KongKing and not KingKong?

Common Java Multi-threading Mistakes

The correct answer is "KongKing" and this is because of one typo in code. The intention of this code is to create a multi-threaded program, but because of it actually turned into a single-threaded program.

In Java, though it is true that calling Thread.start() will call method but complete truth is that calling start() actually creates a new thread, and that new thread executes the run() method. If you directly call the run() method then no new thread will be created and the thread which is running the code will go to run() and execute it fist and then come back to it's previous point.

Like in this case, the main thread will execute run() method first, and thus print "Kong" before coming back and printing "King", that's why the output is "KongKing". When I quizzed about these to some programmer who was otherwise good but got this answer incorrect insisted that run() will call on a new thread because they are calling as where t is new thread object.

So apart from a typo, this is the key misconception some Java programmer has. This is even more fundamental in nature because it highlights thedifference between code and thread. Here definitely run() is called on t, which is a new thread, but the thread which is executing code is not thread t, but main thread. t is not yet started because you have not called the start() method.

If you copy past above code in Eclipse IDE and debug it you will see the truth, as shown below.

How to debug Multi-threading Programs in Eclipse

You can see that we have put the breakpoint right at the point where the run() method is called i.e. When you step Into this method, you will see that themain thread is executing run() method and not the new thread.

Now if we just changed the to t.start(), your program will become multi-threaded and a new thread will be created when the main thread will execute line t.start(), later run() method will be called in this new thread, here is the screenshot of that.

Difference between Start and Run Method in Java thread

That's all in the first post of my new series of common Java Multi-threading mistakes. Always use start() method to start new threads and make your program multi-threaded, don't call run() method directly. The compiler doesn't prevent you but it creates subtle bugs. By the way, thedifference between start() and run() method is also a very common question on Java interview.

Let me know how do you find this article and don't forget to share what multi-threading issues you have faced and what lessons you have learned from them. On a closing note, I would share one important tip to understand multi-threading better, debug it.

Yes debugging will tell you how many threads are currently executing your code, you can see their stack trace, values of variables they are holding, and on which lock they are locking. Debugging a multithreaded program is not easy, but once you do it a couple of times, you will find it immensely useful.

Further Learning

Multithreading and Parallel Computing in Java

Java Concurrency in Practice - The Book

Applying Concurrency and Multi-threading to Common Java Patterns

Java Concurrency in Practice Course by Heinz Kabutz

No comments for "Common Multi-threading Mistakes in Java - Calling run() instead of start()"