Common Multi-Threading Mistakes Inwards Coffee - Calling Run() Instead Of Start()

Writing multi-threaded together with concurrent programs is non easy, non fifty-fifty inward Java.  Even senior developers, including myself, brand mistakes field writing concurrent Java applications. This is every bit good 1 of the trickiest expanse of Java programming language, where misconceptions outnumbers concepts. Considering amount of misconception an average Java programmers has close multi-threading together with concurrency, I idea to start a novel serial close common multi-threading mistakes done past times Java programmers; what is ameliorate agency to larn from mutual existent give-and-take mistakes. Learning from mistakes has around other call Experience, but if y'all alone larn from your mistakes so at that topographic point is alone express things y'all tin learn, but if y'all larn from other peoples mistake, y'all tin larn much to a greater extent than inward brusk bridge of time. Have y'all e'er thought, Why writing multi-threaded code is difficult? IMHO, primarily argue for this is that it multi-threading makes it hard for a code to beak for itself. Programmer read code sequentially to empathise how it's executed, but it is alone right if 1 together with alone 1 thread is executing it. That's why Single threaded code are slow to read together with debug. As shortly every bit ii threads comes into picture, It acquire really hard to brand prediction close how your code behave, particularly inward the absent of whatsoever synchronization rules e.g. rules enforced past times Java Memory Model. Without JMM you tin non brand right prediction close your code inward a multi-threaded environment, because it's possible for 1 thread to cease at arbitrary indicate together with around other thread at dissimilar point. Situation becomes fifty-fifty to a greater extent than tricky if those threads are sharing information betwixt them e.g. inward cast of objects, a poorly written multi-threaded computer programme tin crusade deadlock, race condition together with responsiveness issues, which volition preclude a Java application to fulfil it's promise. I hope, inward this serial nosotros tin larn from each other's fault together with accept a measuring frontward on writing right multi-threaded application inward Java.


Using Run Instead of Start

I am starting amongst 1 of the simplest example, this is really mutual mistakes past times junior programmers together with caused past times one-half knowledge. They know that anything written inward run() method of Runnable interface or Thread class volition execute inward around other thread, but doesn't know how to create around other thread inward JVM.


Consider next code :

class KingKong {      public static synchronized void main(String[] args) {         Thread t = new Thread() {             public void run() {                 kong();             }         };          t.run();         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 fourth dimension error

We had this query inward our Java written seek together with y'all volition survive surprised past times the per centum of answers, whopping 50% answers It varies, 10% says compile fourth dimension error, around other 15% picks reply a, KingKong together with residue of 25% chooses KongKing. We every bit good inquire to write explanation of why they guide a particular answer, merely to avoid picking mortal who is guessing their way. The 50% developer, who chooses It varies, mentioned that there is no guarantee when a thread volition start, so it possible that if main thread finishes starting fourth dimension it volition impress KongKing together with if novel thread executes earlier primary thread. Wow, what do y'all tell close these developers, seems a decent lot of programmer who knows around role of multi-threading but overlooked critical detail. The side past times side 10% programmer, who chose Compile fourth dimension error were unsure whether main method tin survive synchronized or not together with idea that compiler volition non like. Next 15% says because "King" comes starting fourth dimension inward code, it volition survive printed starting fourth dimension together with "Kong" volition survive printed later. The Last 25% who chose "KongKing" are the people who got it correct. We were literally disappointed amongst these numbers because it wasn't such a hard of tricky question, but I handgrip around fourth dimension it's hard to spot a typo together with that's what makes this error really hard to debug.


Why Code Print KongKing together with non KingKong?

threaded together with concurrent programs is non slow Common Multi-threading Mistakes inward Java - Calling run() instead of start()
Correct reply is "KongKing" together with this is because of 1 typo inward code. Intention of this code is to create a multi-threaded program, but because of t.run() it truly turned into a unmarried threaded program. In Java, though it is truthful that calling Thread.start() volition telephone outcry upwards Runnable.run() method but consummate truth is that calling start() truly creates a novel thread, together with that novel thread executes the run() method. If y'all direct telephone outcry upwards the run() method so no novel thread volition survive created together with the thread which is running the code volition expire to run() together with execute it fist together with so comeback to it's previous point. Like inward this case, primary thread volition execute run() method first, together with hence impress "Kong" earlier coming dorsum together with printing "King", that's why output is "KongKing". When I quizzed close these to around programmer who were otherwise expert but got this reply wrong insisted that run() volition telephone outcry upwards on novel thread because they are calling every bit t.run() where t is novel thread object. So apart from typo, this is the key misconception around Java programmer has. This is fifty-fifty to a greater extent than key inward nature because it highlight difference betwixt code together with thread. Here definitely run() is called on t, which is a novel thread, but the thread which is executing code is non thread t, but main thread. t is non silent started because y'all receive got non called the start() method. If y'all copy past times to a higher house code inward Eclipse IDE together with debug it y'all volition run into the truth, every bit shown below.
threaded together with concurrent programs is non slow Common Multi-threading Mistakes inward Java - Calling run() instead of start()

You tin run into that nosotros receive got lay the breakpoint right at the indicate where run() method is called i.e. t.run(). When y'all measuring Into this method, y'all volition run into that main thread is executing run() method together with non the new thread. Now if nosotros merely changed the t.run() to t.start(), your computer programme volition acquire multi-threaded together with a novel thread volition survive created when primary thread volition execute line of piece of occupation t.start(), later on run() method volition survive called inward this novel thread, hither is the screenshot of that.
threaded together with concurrent programs is non slow Common Multi-threading Mistakes inward Java - Calling run() instead of start()


That's all inward starting fourth dimension ship of my novel serial of common Java Multi-threading mistakes. Always utilisation start() method to start novel threads together with brand your computer programme multi-threaded, don't telephone outcry upwards run() method directly. Compiler doesn't preclude y'all but it create subtle bugs. By the way, difference betwixt start() together with run() method is every bit good really mutual query on Java interview. Let me know how do y'all honour this article together with don't forget to portion what multi-threading issues y'all receive got faced together with what lessons y'all receive got learned from them. On closing note, I would portion 1 of import tip to empathise multi-threading better, debug it. Yes debugging volition tell y'all how many threads are currently executing your code, y'all tin run into their stack trace, values of variables they are belongings together with on which lock they are locking. Debugging multi-threaded computer programme is non easy, but 1 time y'all do it duo of times, y'all volition honour it immensely useful.

Further Learning
Multithreading together with Parallel Computing inward Java
Java Concurrency inward Practice - The Book
Applying Concurrency together with Multi-threading to Common Java Patterns
Java Concurrency inward Practice Course past times Heinz Kabutz


Komentar

Postingan populer dari blog ini

3 Examples Of Parsing Html File Inwards Coffee Using Jsoup

Why You Lot Should Command Visibility Of Shape Too Interface Inward Java