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

Writing multi-threaded too concurrent programs is non easy, non fifty-fifty inwards Java.  Even senior developers, including myself, brand mistakes piece writing concurrent Java applications. This is likewise i of the trickiest expanse of Java programming language, where misconceptions outnumbers concepts. Considering amount of misconception an average Java programmers has nearly multi-threading too concurrency, I idea to start a novel serial nearly common multi-threading mistakes done past times Java programmers; what is amend agency to acquire from mutual existent give-and-take mistakes. Learning from mistakes has to a greater extent than or less other call Experience, but if you lot alone acquire from your mistakes too so in that place is alone express things you lot tin learn, but if you lot acquire from other peoples mistake, you lot tin acquire much to a greater extent than inwards brusk bridge of time. Have you lot 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 utter for itself. Programmer read code sequentially to empathise how it's executed, but it is alone right if i too alone i thread is executing it. That's why Single threaded code are slowly to read too debug. As before long equally ii threads comes into picture, It drib dead rattling hard to brand prediction nearly how your code behave, particularly inwards the absent of whatsoever synchronization rules e.g. rules enforced past times Java Memory Model. Without JMM you tin non brand right prediction nearly your code inwards a multi-threaded environment, because it's possible for i thread to halt at arbitrary indicate too to a greater extent than or less 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. inwards cast of objects, a poorly written multi-threaded computer program tin movement deadlock, race condition too responsiveness issues, which volition foreclose a Java application to fulfil it's promise. I hope, inwards this serial nosotros tin acquire from each other's error too receive got a measuring forrad on writing right multi-threaded application inwards Java.


Using Run Instead of Start

I am starting amongst i of the simplest example, this is rattling mutual mistakes past times junior programmers too caused past times one-half knowledge. They know that anything written inwards run() method of Runnable interface or Thread class volition execute inwards to a greater extent than or less other thread, but doesn't know how to create to a greater extent than or less other thread inwards 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 inquiry inwards our Java written examine too you lot volition travel surprised past times the percent of answers, whopping 50% answers It varies, 10% says compile fourth dimension error, to a greater extent than or less other 15% picks reply a, KingKong too residual of 25% chooses KongKing. We likewise inquire to write explanation of why they select a particular answer, only to avoid picking somebody 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 outset it volition impress KongKing too if novel thread executes earlier original thread. Wow, what do you lot state nearly these developers, seems a decent lot of programmer who knows to a greater extent than or less work of multi-threading but overlooked critical detail. The adjacent 10% programmer, who chose Compile fourth dimension error were unsure whether main method tin travel synchronized or not too idea that compiler volition non like. Next 15% says because "King" comes outset inwards code, it volition travel printed outset too "Kong" volition travel 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 concord to a greater extent than or less fourth dimension it's hard to topographic point a typo too that's what makes this error rattling hard to debug.


Why Code Print KongKing too non KingKong?

threaded too concurrent programs is non slowly Common Multi-threading Mistakes inwards Java - Calling run() instead of start()
Correct reply is "KongKing" too this is because of i typo inwards code. Intention of this code is to create a multi-threaded program, but because of t.run() it genuinely turned into a unmarried threaded program. In Java, though it is truthful that calling Thread.start() volition telephone outcry upward Runnable.run() method but consummate truth is that calling start() genuinely creates a novel thread, too that novel thread executes the run() method. If you lot straight telephone outcry upward the run() method too so no novel thread volition travel created too the thread which is running the code volition drib dead to run() too execute it fist too and so comeback to it's previous point. Like inwards this case, original thread volition execute run() method first, too thence impress "Kong" earlier coming dorsum too printing "King", that's why output is "KongKing". When I quizzed nearly these to to a greater extent than or less programmer who were otherwise adept but got this reply wrong insisted that run() volition telephone outcry upward on novel thread because they are calling equally t.run() where t is novel thread object. So apart from typo, this is the key misconception to a greater extent than or less Java programmer has. This is fifty-fifty to a greater extent than cardinal inwards nature because it highlight difference betwixt code too 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 nevertheless started because you lot receive got non called the start() method. If you lot copy past times inwards a higher house code inwards Eclipse IDE too debug it you lot volition encounter the truth, equally shown below.
threaded too concurrent programs is non slowly Common Multi-threading Mistakes inwards Java - Calling run() instead of start()

You tin encounter that nosotros receive got set the breakpoint right at the indicate where run() method is called i.e. t.run(). When you lot measuring Into this method, you lot volition encounter that main thread is executing run() method too non the new thread. Now if nosotros only changed the t.run() to t.start(), your computer program volition drib dead multi-threaded too a novel thread volition travel created when original thread volition execute occupation t.start(), afterwards run() method volition travel called inwards this novel thread, hither is the screenshot of that.
threaded too concurrent programs is non slowly Common Multi-threading Mistakes inwards Java - Calling run() instead of start()


That's all inwards outset postal service of my novel serial of common Java Multi-threading mistakes. Always work start() method to start novel threads too brand your computer program multi-threaded, don't telephone outcry upward run() method directly. Compiler doesn't foreclose you lot but it create subtle bugs. By the way, difference betwixt start() too run() method is likewise rattling mutual inquiry on Java interview. Let me know how do you lot honor this article too don't forget to part what multi-threading issues you lot receive got faced too what lessons you lot receive got learned from them. On closing note, I would part i of import tip to empathise multi-threading better, debug it. Yes debugging volition tell you lot how many threads are currently executing your code, you lot tin encounter their stack trace, values of variables they are asset too on which lock they are locking. Debugging multi-threaded computer program is non easy, but in i lawsuit you lot do it span of times, you lot volition honor it immensely useful.

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


Belum ada Komentar untuk "Common Multi-Threading Mistakes Inwards Coffee - Calling Run() Instead Of Start()"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel