/Core Java

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+01: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

An introduction to Lambdas in Java 8

An introduction to Lambdas in Java 8 There are a number of exciting new features in Java 8 that have changed the language for the better, but lambda expressions in particular stand out. What is a Lambda Expression? In simple terms a lambda expression is a piece of code that can be passed to another method as a parameter, and then executed by the receiving method. The ability to parametrise behaviour is not new to Java and is something you've probably done many times with anonymous classes. Lambdas however provide a more elegant means of passing code to another method for execution. To show you the [...]

By |2019-02-28T07:23:17+01:00February 8th, 2015|Core Java|0 Comments