Loading...

How to use wait, notify and notifyAll in Java - Producer Consumer Example

You can use wait, notify and notifyAll methods to communicate between threads in Java. For example, if you have two threads running in your program e.g.Producer and Consumer then producer thread can communicate to consumer that it can start consuming now because there are items to consume in queue. Similarly a consumer thread can tell producer that it can also start putting items now because there is some space in queue, which is created as a result of consumption. A thread can use wait() method to pause and do nothing depending upon some condition. For example, in producer consumer problem, producer thread should wait if queue is full and consumer thread should wait if queue is empty. If some thread is waiting for some condition to become true, you can use notify and notifyAll methods to inform them that condition is now changed and they can wake up. Both notify() and notifyAll() method sends notification but notify sends notification to only one of the waiting thread, no guarantee which thread will receive notification and notifyAll() sends notification to all threads. So if only one thread is waiting on an object lock, also known as monitor then both notify and notifyAll wil send notification to it. If multiple threads are waiting on a monitor then notify will only inform one of the lucky thread and rest will not receive any notification, but notifyAll will inform all threads. In this Java multi-threading tutorial you will learn how to use wait, notify and notifyAll() method in Java to implement inter thread communication by solving producer consumer problem. BTW, if you are serious about mastering concurrency and multi-threading, I strongly suggest you to read Java Concurrency in Practice by Brian Goetz, without reading that book your journey to Java multi-threading is not complete. Its probably one of the most recommended book to Java developers.

Java Lock and Condition Example using Producer Consumer Solution

You can also solve producer consumer problem by using new lock interface and condition variable instead of using synchronized keyword and wait and notify methods.  Lock provides an alternate way to achieve mutual exclusion and synchronization in Java. Advantage of Lock over synchronized keyword is well known, explicit locking is much more granular and powerful than synchronized keyword, for example, scope of lock can range from one method to another but scope of synchronized keyword cannot go beyond one method. Condition variables are instance of java.util.concurrent.locks.Condition class, which provides inter thread communication methods similar to wait, notify and notifyAll e.g. await(), signal() and signalAll(). So if one thread is waiting on a condition by calling condition.await() then once that condition changes, second thread can call condition.signal() or condition.signalAll() method to notify that its time to wake-up, condition has been changed. Though Lock and Condition variables are powerful they are slightly difficult to use for first timers. If you are used to locking using synchronized keyword, you will using Lock painful because now it becomes developer's responsibility to acquire and release lock. Anyway, you can follow code idiom shown here to use Lock to avoid any concurrency issue. In this article, you will learn how to use Lock and Condition variables in Java by solving classic Producer Consumer problem. In order to deeply understand these new concurrency concepts, I also suggest to take a look at Java 7 Concurrency Cookbook, Its one of the best book in Java concurrency with some good non trivial examples.

How to use Callable and Future in Java? Example

Callable interface was added in Java 5 to complement existing Runnable interface, which is used to wrap a task and pass it to a Thread or thread pool for asynchronous execution. Callable actually represent an asynchronous computation, whose value is available via Future object. All the code which needs to be executed asynchronously goes into call() method. Callable is also a single abstract method type (SAM type), so it can be used along with lambda expression on Java 8. Both Callable and Future are parametric type and can be used to wrap classes like Integer, String or anything else. When you pass a Callable to thread pool, it choose one thread and execute the Callable. It immediately return a Future object which promises to hold result of computation once done. You can then call get() method of Future, which will return result of computation or block if Computation is not complete. If you don't like indefinite blocking then you can also use overloaded get() method with timeout. Future also allows you to cancel the task if its not started or interrupt if its started. We will see, how we can calculate factorial of large number using Callable and Future in Java. BTW, if you are serious about mastering concurrency API of Java, I suggest you to also take a look at one of the best book on the subject, Java Concurrency in Practice by Brian Goetz. It is one of the book I keep refer whenever I have a doubt or want to refresh my knowledge.

Top 10 Java Multithreading and Concurrency Best Practices

Writing concurrent code is hard and and testing correctness with concurrency is even harder. Though Java programming language provides lots of synchronization and concurrency support from language to API level, it's eventually comes to individual's diligent and expertise to write bug free Java concurrency code. These Java concurrency and multi-threading best practices are collection of some well known tips, which helps you to write better concurrency code in Java. Some of you, may be familiar with these tips, it's often worth to revise them in couple of years. These Java multi-threading and concurrency tips are from my own learning and usage, and also inspired by reading books like Effective Java and Java Concurrency in Practice in particular. I suggest reading Java Concurrency Practice two times to every Java developer, yes, you heard it correctly, TWO times. Concurrency is confusing and difficult to comprehend, much like Recursion to few programmers; and in one reading, you might not get all of it.

How to use Future and FutureTask in Java Concurrency with Example

Future and FutureTask in Java allows you to write asynchronous code. Future is a general concurrency abstraction, also known as promise, which promises to return a result in future. In asynchronous programming, main thread doesn't wait for any task to finished, rather it hand over the task to workers and move on. One way of aynchronous processing is using callback methods. Future is another way to write asynchronous code. By using Future and FutureTask, you can write method which does long computation but return immediately. Those method, instead of returning result, return a Future object. You can later get result by calling Future.get() method, which will return object of type T, where T is what Future object is holding . One example of Future is submit() method of ExecutorService, which immediately return a Future object. By the way, Future and FutureTask are available in java.util.concurreent package from Java 1.5. Also, Future is and interface and FutureTask is an implementation or RunnableFuture, which can be used as Runnable interface, thus, can be passed to ExecutorService. In this Java concurrency tutorial, we will learn how to use Future and FutureTask in Java.

How to Use Locks in Multi-threaded Java Program

Many Java programmers confused themselves like hell while writing multi-threaded Java programs e.g. where to synchronized? Which Lock to use? What Lock to use etc. I often receive request to explain about how to use Locks in Java, so I thought to write a simple Java program, which is multi-threaded and uses rather new Lock interface. Remember Lock is your tool to guard shared resource 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 synchronized keyword. If you have never written any multi-threading program, then I suggest first start with synchronized keyword because it’s easier to use them. Once you are familiar with working of multi-threading program e.g. How threads share data, how inter thread communication works, you can start with Lock facility. As I told you Lock is an interface, so we cannot use it directly, instead we need to use its implementation class. Thankfully Java comes with two implementation of java.util.concurrent.locks.Lock interface, ReentrantLock and ReentrantReadWriteLock, later provides two more inner implementation known as ReentrantReadWriteLock.ReadLock and ReentrantReadWriteLock.WriteLock. For our simple multi-threaded Java program's purpose ReentrantLock is enough.

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 programmers 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, primarily 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 comes into picture, It become very difficult to make prediction about how your code behave, especially in the absent of any synchronization rules e.g. rules enforced by Java Memory Model. Without JMM you can not make correct prediction about your code in a multi-threaded environment, because it's possible for one thread to stop at arbitrary point and another thread at different point. 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 fulfil it's promise. I hope, in this series we can learn from each other's mistake and take a step forward on writing correct multi-threaded application in Java.

Top 50 Java Thread Interview Questions Answers for Experienced

You go to any Java interview, senior or junior, experience or freshers,  you are bound to see couple of questions from thread, concurrency and multi-threading. In fact this built-in concurrency support is one of the strongest point of Java programming language and helped it to gain popularity among enterprise world and programmers equally. Most of lucrative Java developer position demands excellent core Java multi-threading skills and experience on developing, debugging and tuning high performance low latency concurrent Java applications. This is the reason, it is one of the most sought after skill on interviews. In a typical Java interview, Interviewer slowly starts from basic concepts of Thread by asking questions like, why you need threads, how to create threads, which one is better way to create threads e.g. by extending thread class or implementing Runnable and then slowly goes into Concurrency issues, challenges faced during development of concurrent Java applications, Java memory model, higher order concurrency utilities introduced in JDK 1.5, principles and design patterns of concurrent Java applications, classical multi-threading problems e.g. producer consumer, dining philosopher, reader writer or simply bounded buffer problems. Also I strongly recommend to any Java developer to read Effective Java and Java Concurrency in Practice twice before going to interview. They are not only help you to answer questions better but also help you to present your idea clearly.

SynchronousQueue Example in Java - Produer Consumer Solution

SynchronousQueue is special kind of BlockingQueue in which each insert operation must wait for a corresponding remove operation by another thread, and vice versa. When you call put() method on SynchronousQueue it blocks until another thread is there to take that element out of the Queue. Similarly, if a thread tries to remove an element and no element is currently present, that thread is blocked until another thread puts an element into the queue. You can correlated SynchronousQueue with athletes (threads) running with Olympic torch, they run with torch (object need to be passed) and passes it to other athlete waiting at other end. If you pay attention to the name, you will also understand that it is named SynchronousQueue with a reason, it passes data synchronously to other thread; it wait for the other party to take the data instead of just putting data and returning (asynchronous operation). If you are familiar with CSP and Ada, then you know that synchronous queues are similar to rendezvous channels. They are well suited for hand-off designs, in which an object running in one thread must sync up with an object running in another thread in order to hand it some information, event, or task. In earlier multi-threading tutorials we have learned how to solve producer consumer problem using wait and notify, and BlockingQueue and in this tutorial we will learn how to implement producer consumer design pattern using synchronous queue. This class also supports an optional fairness policy for ordering waiting producer and consumer threads. By default, this ordering is not guaranteed. However, a queue constructed with fairness property set to true grants threads access in FIFO order.

Inter Thread Communication in Java using Wait Notify Example

Wait and notify methods in Java are used for inter-thread communication i.e. if one thread wants to tell something to another thread, it uses notify() and notifyAll() method of java.lang.Object. Classical example of wait and notify method is Producer Consumer design pattern, where One thread produce and put something on shared bucket, and then tell other thread that there is an item for your interest in shared object, consumer thread than pick than item and do his job, without wait() and notify(), consumer thread needs to be busy checking, even if there is no change in state of shared object. This brings an interesting point on using wait and notify mechanism, a call to notify() happens, when thread changed state of shared object i.e. in this case producer change bucket from empty to not empty, and consumer change state from non empty to empty. Also wait and notify method must be called from synchronized context, wondering why, read this link for some reasons which makes sense. Another important thing to keep in mind while calling them is, using loop to check conditions instead of if block. This is really tricky for beginners, which often don't understand difference and wonders why wait and notify get called form loops. Joshua Bloch has a very informative item on his book Effective Java, I strongly suggest reading that. In short, a waiting thread may woke up, without any change in it's waiting condition due to spurious wake up. For example, if a consumer thread, which is waiting because shared queue is empty, gets wake up due to a false alarm and try to get something from queue without further checking whether queue is empty or not than unexpected result is possible. Here is standard idiom for calling wait, notify and notifyAll methods in Java :

How to call wait method in Java :

How to create Thread Pools using Java 1.5 Executor Framework - Example Tutorial

Java 1.5 introduced Thread pool in Java in form of Executor framework, which allows Java programmer to decouple submission of task to execution of task. If you are doing server side programming in Java than Thread pool is an important concept to maintain scalability, robustness and stability of system. For those, who are not familiar with thread pool in Java or concept of thread pool here is one liner, Thread pool in Java is pool of worker threads, which is ready to perform any task given to them, mostly in form of implementation of Runnable or Callable interface. Since Java supports multithreading in programming language itself, it allows multiple thread to run concurrently and perform parallel processing of task. In this article we will learn following things about thread pool in Java :
  1. What is Thread pool in Java?
  2. Why do we need Thread pool in Java ?
  3. What is Executor framework in Java 5?
  4. How to create fixed size thread pool using Executor framework in Java?
  5. Benefits of using Thread Pool in Java?

ReentrantLock Example in Java, Difference between synchronized vs ReentrantLock

ReentrantLock in Java is added on java.util.concurrent package in Java 1.5 along with other concurrent utilities like CountDownLatch, Executors and CyclicBarrier. ReentrantLock is one of the most useful addition in Java concurrency package and several of concurrent collection classes from java.util.concurrent package is written using ReentrantLock, including ConcurrentHashMap, see How ConcurrentHashMap works in Java for more details. Two key feature of ReentrantLock, which provides more control on lock acquisition is trying to get a lock with ability to interrupt, and a timeout on waiting for lock, these are key for writing responsive and scalable systems in Java. In short, ReentrantLock extends functionality of synchronized keyword in Java and open path for more controlled locking in Java. 

In this Java concurrency tutorial we will learn :
  • What is ReentrantLock in Java ?
  • Difference between ReentrantLock and synchronized keyword in Java?
  • Benefits of using Reentrant lock in Java?
  • Drawbacks of using Reentrant lock in concurrent program?
  • Code Example of ReentrantLock in Java?

How to Join Multiple Threads in Java - Thread Join Example

Join method from Thread class is an important method and used to impose order on execution of multiple Threads. Concept of joining multiple threads is very popular on  mutithreading interview question. Here is one of such question, “You have three threads T1, T2 and T3, How do you ensure that they finish in order T1, T2, T3 ?. This question illustrate power of join method on multithreaded programming. Unlike classical thread questions like difference between wait and sleep method or solving producer consumer problem in Java, This one is bit tricky. You can do this by using join method, by calling T1.join() from T2 and T2.join() from T3. In this case thread T1 will finish first, followed by T2 and T3. In this Java multithreading tutorial we will have a closer look on join method with a simple example. Idea is to illustrate how join method works in simple words. By the way from Java 5 onwards you can also use CountDownLatch and CyclicBarrier classes to implement scenarios like one thread is waiting for other threads to finish there task.

How to write Thread-Safe Code in Java

thread-safety or thread-safe code in Java refers to code which can safely be used or shared in concurrent or multi-threading environment and they will behave as expected. any code, class or object which can behave differently from its contract on concurrent environment is not thread-safe. thread-safety is one of the risk introduced by using threads in Java and I have seen java programmers and developers struggling to write thread-safe code or just understanding what is thread-safe code and what is not? This will not be very detailed article on thread-safety or low level details of synchronization in Java instead we will keep it simple and  focus on one example of non thread-safe code and try to understand what is thread-safety and how to make an code thread-safe.

How Volatile in Java works? Example of volatile keyword in Java

How to use Volatile keyword in Java
What is volatile variable in Java and when to use Volatile variable in Java is famous multi-threading interview question in Java interviews. Though many programmer knows what is a volatile variable but they fail on second part i.e. where to use volatile variable in Java as its not common to have clear understanding and hands-on on volatile in Java. In this tutorial we will address this gap by providing simple example of volatile variable in Java and discussing some when to use Volatile variable in Java. Any way Volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory. So if you want to share any variable in which read and write operation is atomic by implementation e.g. read and write in int or boolean variable you can declare them as volatile variable. From Java 5 along with major changes like Autoboxing, Enum, Generics and Variable arguments , Java introduces some change in Java Memory Model (JMM), Which guarantees visibility of changes made by one thread to another also as "happens-before" which solves the problem of memory writes that happen in one thread can "leak through" and be seen by another thread. Java volatile keyword cannot be used with method or class and it can only be used with variable. Java volatile keyword also guarantees visibility and ordering , after Java 5 write to any volatile variable happens before any read into volatile variable. By the way use of volatile keyword also prevents compiler or JVM from reordering of code or moving away them from synchronization barrier.

How to Implement Thread in Java with Example

How to implement Thread in Java
In my opinion Thread is one of the most important feature of Java programming language which helped it to become the most popular programming language. I remember, when I first started learning Java in one of the programming class on India how important Thread was portrait and how much emphasis given on clear understanding of multi-threading. It’s still popular and one of most sought after skill in Java programmer because writing concurrent and multi-threaded application in Java is challenging, despite Java providing excellent support at language level using synchronized and volatile keyword. Main problem with using multiple threads and writing multi-threaded code is issues related to concurrency e.g. deadlock, livelock, race conditions etc, It takes lot of effort to implement multi-threading correctly in Java application. In this core Java tutorial I will share my experience on different way of implementing Thread in Java;  By the way difference between Thread and Runnable in Java is also a very common core Java interview question and asked mostly during junior level Java interview. After reading this tutorial, you will not only able to create and start thread but also able to answer what is difference in two ways of implementing thread in Java, by implementing Runnable interface or by extending Thread class.