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 equally good i of the trickiest expanse of Java programming language, where misconceptions outnumbers concepts. Considering amount of misconception an average Java programmers has almost multi-threading too concurrency, I idea to start a novel serial almost 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 only about other yell Experience, but if you lot entirely acquire from your mistakes too so at that spot is entirely 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 always 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 talk for itself. Programmer read code sequentially to empathize how it's executed, but it is entirely right if i too entirely i thread is executing it. That's why Single threaded code are slowly to read too debug. As presently equally 2 threads comes into picture, It expire real hard to brand prediction almost how your code behave, particularly inwards the absent of whatever synchronization rules e.g. rules enforced past times Java Memory Model. Without JMM you tin non brand right prediction almost your code inwards a multi-threaded environment, because it's possible for i thread to halt at arbitrary indicate too only about 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 programme tin crusade 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 measurement forrad on writing right multi-threaded application inwards Java.
Consider next code :
What Does It Print?
(a) KingKong
(b) KongKing
(c) It varies
(d) Compile fourth dimension error
We had this inquiry inwards our Java written attempt too you lot volition live on surprised past times the percent of answers, whopping 50% answers It varies, 10% says compile fourth dimension error, only about other 15% picks respond a, KingKong too residual of 25% chooses KongKing. We equally good inquire to write explanation of why they conduct a particular answer, only 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 start it volition impress KongKing too if novel thread executes earlier psyche thread. Wow, what do you lot tell almost these developers, seems a decent lot of programmer who knows only about purpose of multi-threading but overlooked critical detail. The adjacent 10% programmer, who chose Compile fourth dimension error were unsure whether main method tin live on synchronized or not too idea that compiler volition non like. Next 15% says because "King" comes start inwards code, it volition live on printed start too "Kong" volition live on 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 only about fourth dimension it's hard to spot a typo too that's what makes this error real hard to debug.
You tin run across that nosotros receive got position the breakpoint right at the indicate where run() method is called i.e. t.run(). When you lot measurement Into this method, you lot volition run across that main thread is executing run() method too non the new thread. Now if nosotros only changed the t.run() to t.start(), your programme volition expire multi-threaded too a novel thread volition live on created when psyche thread volition execute work t.start(), subsequently run() method volition live on called inwards this novel thread, hither is the screenshot of that.
That's all inwards start postal service of my novel serial of common Java Multi-threading mistakes. Always utilization start() method to start novel threads too brand your programme multi-threaded, don't telephone yell 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 equally good real mutual inquiry on Java interview. Let me know how do you lot uncovering 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 empathize multi-threading better, debug it. Yes debugging volition tell you lot how many threads are currently executing your code, you lot tin run across their stack trace, values of variables they are belongings too on which lock they are locking. Debugging multi-threaded programme is non easy, but in i lawsuit you lot do it span of times, you lot volition uncovering 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
Using Run Instead of Start
I am starting amongst i of the simplest example, this is real 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 only about other thread, but doesn't know how to create only about 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 attempt too you lot volition live on surprised past times the percent of answers, whopping 50% answers It varies, 10% says compile fourth dimension error, only about other 15% picks respond a, KingKong too residual of 25% chooses KongKing. We equally good inquire to write explanation of why they conduct a particular answer, only 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 start it volition impress KongKing too if novel thread executes earlier psyche thread. Wow, what do you lot tell almost these developers, seems a decent lot of programmer who knows only about purpose of multi-threading but overlooked critical detail. The adjacent 10% programmer, who chose Compile fourth dimension error were unsure whether main method tin live on synchronized or not too idea that compiler volition non like. Next 15% says because "King" comes start inwards code, it volition live on printed start too "Kong" volition live on 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 only about fourth dimension it's hard to spot a typo too that's what makes this error real hard to debug.
Why Code Print KongKing too non KingKong?
Correct respond 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 yell 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 yell upward the run() method too so no novel thread volition live on created too the thread which is running the code volition expire to run() too execute it fist too and so comeback to it's previous point. Like inwards this case, psyche 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 almost these to only about programmer who were otherwise expert but got this respond wrong insisted that run() volition telephone yell 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 only about 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 even so 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 run across the truth, equally shown below.You tin run across that nosotros receive got position the breakpoint right at the indicate where run() method is called i.e. t.run(). When you lot measurement Into this method, you lot volition run across that main thread is executing run() method too non the new thread. Now if nosotros only changed the t.run() to t.start(), your programme volition expire multi-threaded too a novel thread volition live on created when psyche thread volition execute work t.start(), subsequently run() method volition live on called inwards this novel thread, hither is the screenshot of that.
That's all inwards start postal service of my novel serial of common Java Multi-threading mistakes. Always utilization start() method to start novel threads too brand your programme multi-threaded, don't telephone yell 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 equally good real mutual inquiry on Java interview. Let me know how do you lot uncovering 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 empathize multi-threading better, debug it. Yes debugging volition tell you lot how many threads are currently executing your code, you lot tin run across their stack trace, values of variables they are belongings too on which lock they are locking. Debugging multi-threaded programme is non easy, but in i lawsuit you lot do it span of times, you lot volition uncovering 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