Postingan

Menampilkan postingan dengan label Java multithreading Tutorials

Top 15 Java Multithreading, Concurrency Interview Questions Answers asked in Investment banks

Gambar
Multi-threading and concurrency questions are an essential part of any Java interview. If you are going for any Java interview on any Investment bank e.g. Barclays, Citibank, Morgan Stanley etc for Cash Equities Front Office Java Developer position, you can expect a lot of multi-threading interview questions on your way. Multi-threading and concurrency are favorite topics on Investment banking interviews,  especially on electronic trading development jobs and they grill candidate on many tricky java thread interview questions. They just want to ensure that the guy has solid knowledge of multi-threading and concurrent programming in Java because most of them are in the business of performance which provides them a competitive advantage and it's hard to write correct and robust concurrent code. For example, high volume and low latency Electronic Trading Systems which are used for Direct to Market (DMA) trading are usually concurrent in nature.  Most of the time the focus on micr...

Thread, code and data - Story of a Multithreading Program in Java

Gambar
There are certain things, which you don't learn on academics or training class, you develop those understanding after few years of work experience, and then you realize, it was very basic, how come I had missed that all those years. Understanding of how a multi-threaded Java program executes is one of such things. You definitely have heard about threads, how to start a thread, how to stop a thread, definitions like its independent path of execution, all funky libraries to deal with inter-thread communication, yet when it comes to debugging a multithreaded Java program, you struggle. At least I can say this from my personal experience. Debugging is in my opinion real trainer, you will learn a subtle concept and develop an understanding which will last long, only through debugging. In this article, I am going to talk about three important things about any program execution, not just Java, Thread, code, and data. Once you have a good understanding of how these three work together, it ...

How to avoid deadlock in Java?

Gambar
How to avoid deadlock in Java? Is one of the popular Java interview question and flavor of the season for multi-threading, asked mostly at a senior level with lots of follow up questions. Even though the problem looks very basic but most of the Java developers get stuck once you start going deep. Interview questions start with, "What is a deadlock?" The answer is simple when two or more threads are waiting for each other to release the resource they need (lock) and get stuck for infinite time, the situation is called deadlock. It will only happen in the case of multitasking or multi-threading. How do you detect deadlock in Java? Though this could have many answers, my version is; first I would look at the code if I see a nested synchronized block or calling one synchronized method from other, or trying to get a lock on a different object then there is a good chance of deadlock if a developer is not very careful. Another way is to find it when you actually get dead-locked whil...

What is happens-before in Java Concurrency? An example

Gambar
A couple of days ago, one of my readers messaged me on LinkedIn about a Java interview question he has recently faced - what is the happens-before relationship in Java concurrency? What is the benefit of it, and how exactly it works? He kind of has some ideas about that its related to the Java Memory Model and provides some sort of visibility guaranteed but couldn't explain with conviction to his interviewer, particularly with a code example and was a bit disappointed. He then asked me if I can write an article about it. I said you should have read the Java concurrency in Practice book before the interview, that would have helped, but nonetheless, I liked the idea to just provide a quick overview of what is the happens-before relationship between threads in Java. To understand the happens-before relationship, you need to first understand what problems can occur if the same variable is accessed by multiple threads? particularly if one thread writes into the variable, and one thr...

Top 5 Books to Learn Concurrent Programming and Multithreading in Java - Best, Must Read

Gambar
Books are essential to learning something new, and despite being in the electronic age, where books have lost some shine to internet and blogs, I still read and recommend them to get complete and authoritative knowledge on any topic, e.g., concurrent programming. In this article, I will share five best books to learn concurrent programming in Java . These books cover basics, starting from how to create and start a thread, parallel programming, concurrency design patterns, an advantage of concurrency and of course pitfalls, issues, and problems introduced due to multithreading. Learning concurrent programming is a difficult task, not even in Java but also in other languages like C++ or modern days JVM languages like Groovy, Scala, Closure, and JRuby. Since I have been doing active Java development from more than 10 years, I can say that this is the best language to start with concurrent programming, because of its structure, inbuilt concurrency support in terms of synchronized, volatile...

How to use Fork Join in Java 1.7 - Tutorial with Example

Gambar
What is fork Join framework in Java : Already popular project coin of JDK7 release has presented a lot of good feature e.g automatic resource management, string in switch case, better exception handling in JDK7, etc. On of another important feature to note is fork-join as the name implies it divides one task into several small tasks as a new fork means child and join all the fork when all the sub-tasks complete. Fork/join tasks is “pure” in-memory algorithms in which no I/O operations come into the picture.it is based on a work-stealing algorithm. The concept of fork-join would be much clear by the following diagram. How fork-join comes in existence Java’s most attractive part is it makes things easier and easier.for doing things faster java has given us concurrency concept but dealing with concurrency is not easy because we have to deal with thread synchronization and shared data. When we have to work with a small piece of code it is easy to handle synchronization and atomicity, bu...

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

Gambar
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...

How to Use Locks in Multi-threaded Java Program

Gambar
Many Java programmers confused themselves like hell while writing multi-threaded Java programs like where to synchronized? Which Lock to use? What Lock to use etc. I often receive a request to explain how to use Locks in Java , so I thought to write a simple Java program, which is multi-threaded and uses a rather new Lock interface. Remember Lock is your tool to guard shared resources which can be anything e.g. database, File system, a Prime number Generator or a Message processor. Before using Locks in Java program, it’s also better to learn some basics. Lock is an interface from java.util.concurrent package. It was introduced in JDK 1.5 release as an alternative of the synchronized keyword. If you have never written any multi-threading program, then I suggest the first start with the synchronized keyword because it’s easier to use them. Once you are familiar with working of a multi-threading program like How threads share data, how inter-thread communication works, you can start ...

How to Stop Thread in Java Code Example

Gambar
The thread is one of important Class in Java and multithreading is most widely used a feature,but there is no clear way to stop Thread in Java. Earlier there was a stop method exists in Thread Class but Java deprecated that method citing some safety reason. By default, a Thread stops when execution of run() method finish either normally or due to any Exception.In this article, we will How to Stop Thread in Java by using a boolean State variable or flag. Using a flag to stop Thread is a very popular way  of stopping the thread and it's also safe because it doesn't do anything special rather than helping run() method to finish itself. How to Stop Thread in Java As I said earlier Thread in Java will stop once run() method finished. Another important point is that you can not restart a Thread which run() method has finished already , you will get an IllegalStateExceptio, here is a Sample Code for Stopping Thread in Java. Sample Code to Stop Thread in Java private class Runner exten...

Prefer TimeUnit Sleep over Thread.Sleep - Java Coding Tips

Gambar
What is TimeUnit in Java TimeUnit in Java is a class on java.util.concurrent package, introduced in Java 5 along with CountDownLatch, CyclicBarrier, Semaphore and several other concurrent utilities. TimeUnit provides a human readable version of Thread.sleep() method which can be used in place of former. From long time Thread's sleep() method is standard way to pause a Thread in Java and almost every Java programmer is familiar with that. In fact, sleep method itself is a very popular and has appeared on many Java interviews. The difference between wait and sleep is one of the tough Java questions to answer. I f you have used Thread.sleep() before and I am sure you do, you might be familiar with a fact like it's a static method, it doesn't release the lock when pausing Thread and it throws InterruptedException. But what many of us doesn't consider a potential issue is readability. Thread.sleep() is an overloaded method and accept long millisecond and long nanosecond, w...

How to use Exchanger in Java with Example

Gambar
Hello guys, if you are working in a concurrent Java application then you might have heard about the Exchanger class of java.util.concurrent package. The Exchanger in Java is another concurrency or synchronization utility introduced in Java 1.5 along with CountDownLatch, CyclicBarrier, and Semaphores. As the name suggests, the Exchanger allows two Threads to meet and exchange data at the rendezvous or meeting point. The java.util.Exchanger is a parametric class, which defines and holds the type of object to be exchanged. It has an overloaded method called the exchange(), which is used to exchange objects between threads. This is a blocking method, which means the Thread, which calls the exchange() method wait at exchange point until another Thread arrives. Once another thread arrives, both exchange objects and return from this method. An overloaded version of the exchange method accepts additional TimeUnit object and wait until time out. By the way, you can also interrupt a Thr...

Difference between atomic, volatile and synchronized in Java?

Gambar
Hello guys, a lot of people are asking me about the volatile, synchronized, and volatile variables in Java concurrency. After answering them individually on Facebook and LinkedIn, I thought to write this article. In this Java multi-threading tutorial, we will learn about the difference between atomic, volatile, and synchronized variables in Java . Though there are a lot of articles, posts, books, courses, and tutorials already exist on Java concurrency and synchronization, where different people have tried to explain concurrency concepts, but unfortunately, multi-threading and concurrency concepts are still hard to grasp, especially the volatile variables. Even though all three, atomic, volatile, and synchronized helps to avoid multi-threading issues, they are entirely different from each other. Before seeing the difference between them, let's understand what does synchronized, volatile, and atomic variables in Java provides. 1. Synchronized keyword in Java 1) Provides mutual exc...