Multithreading in Swing

Swing programming is not all about creating windows, labels, and buttons. Creating interfaces is only a part of Swing programmers’ job. These interfaces are just a way for the user to interact with the system. You need to understand here that writing a GUI application is more like writing two applications. You always keep the frontend separate from the background tasks.

Concurrent queues

One of the most popular kinds of concurrent collections is a concurrent queue. It is often used to organize some kind of communication between multiple threads within an application by exchanging some data (messages, tasks, unit of works, or something else). To achieve it, several threads should have a reference to a common queue and invoke its methods. You already know that a queue is a…

Thread-safe maps

Welcome back, traveler, on your journey to the depths of concurrency! Remember one of your friends called HashMap? Today it’s time to know how to work with the key-value concept in a multithreaded environment. Thread-safe maps are quite popular. Imagine you implement a cache based on a map. You have two writer threads and one reader thread. If you use HashMap, there is no guarantee that the…

CopyOnWriteArrayList

You are becoming a more experienced developer and conquering the peaks of multithreading. And today, our guest is the CopyOnWriteArrayList class, the member of the java.util.concurrent package. Look closely at the name: ArrayList plus the copy-on-write technique. Together, they give you a thread-safe representation of the ArrayList class.

Timers

The Timer class is used in situations where we want to perform time-related activities, such as scheduling a task to run at a specific time or repeating a task at a specific time interval. When we create a timer, we will instruct it on what code to run using a special class called TimerTask. This class implements a method called run, which will define the code that is executed when…

Interruptions

A thread terminates when its run method stops. Sometimes you may have to terminate a task that is being executed, for example when shutting down an application with multiple threads. Java provides a mechanism called interruptions for requesting a thread to stop or to do something else. Interruption does not force a thread to react immediately but notifies it about such demand.

Executors

We’ve already learned how to create threads by extending the Thread class or implementing the Runnable interface. Both ways allow you to create an object that represents a thread and start it to perform a piece of code in a separated thread. While it is easy to create several threads and start them, it becomes a problem when your application has hundreds or even thousands of threads running concurrently.