Java Concurrency – Synchronization

Java Concurrency - Synchronization In my last post we looked at running tasks across multiple threads, asynchronously using the ExecutorService. Accessing and manipulating an object from multiple threads simultaneously can pose a problem when the object in question holds state. If multiple threads attempt to modify shared state, behaviour can become unpredictable and result in data being left in an inconsistent state. Unsynchronized Code Take the simple BankAccount class below. It holds state in the form of a balance, which can be increased and decreased using the credit and debit methods respectively. When used in a single threaded context this object will behave as expected, crediting and debiting the amounts specified. public class BankAccount [...]

By |2019-02-11T16:55:59+00:00April 12th, 2017|Core Java|0 Comments

Java Concurrency – Multi Threading with ExecutorService

Multi Threading with ExecutorService In this post we'll look how the ExeutorService can be used to run multi-threaded asynchronous tasks. We'll start by creating threads directly and then move on to explore the ExeutorService and how it can be used to simplify things. Creating Threads Directly Before the Executor API came along, developers were responsible for instantiating and managing threads directly. Let's look at a simple example below. /** * Call 2 expensive methods on separate threads * * @throws InterruptedException */ public void doMultiThreadedWork() throws InterruptedException { /* create Runnable using anonymous inner class */ Thread t1 = new Thread(new Runnable() { public void [...]

By |2019-06-20T08:21:26+01:00March 28th, 2017|Core Java|0 Comments
Go to Top