Sharing numeric values across threads using Java 8 LongAdder

In this post we saw how to share primitive values across threads using the various atomic objects in the java.util.concurrent.atomic package. The example code demonstrated the AtomicInteger object which is the thread-safe variant of a “normal” integer. Mathematical operations like adding a value to an integer are carried out atomically for that object. This means that the low-level instructions involved in adding two integers are carried out as one unit without the risk of another interfering thread. The same package includes atomic versions of other primitive values such as AtomicBoolean or AtomicLong.

In this post we’ll take a quick look at an addition in Java 8 relevant to sharing integers, longs and doubles.

Read more of this post

Sharing primitives across threads in Java using atomic objects

Threading and parallel execution are popular choices when making applications more responsive and resource-efficient. Various tasks are carried out on separate threads where they either produce some result relevant to the main thread or just run in the background “unnoticed”. Often these tasks work autonomously meaning they have their own set of dependencies and variables. That is they do not interfere with a resource that is common to 2 or more threads.

However, that’s not always the case. Imagine that multiple threads are trying to update the same primitive like an integer counter. They perform some action and then update this counter. In this post we’ll see what can go wrong.

Read more of this post

Getting the result of the first completed parallel task in Java

In this post we saw how to delegate one or more parallel tasks to different threads and wait for all of them to complete. We pretended that 4 different computations took 1,2,3 and respectively 4 seconds to complete. If we execute each calculation one after the other on the same thread then it takes 10 seconds to complete them all. We can do a lot better by assigning each operation to a separate thread and let them run in parallel. The Future and Callable of T objects along with a thread pool make this very easy to implement.

There are situations where we only need the result from 1 parallel operation. Imagine that it’s enough to complete 1 of the four computations in the example code so that our main thread can continue. We don’t know how long each operation will take so we let them have a race. The one that is executed first returns its value and the rest are interrupted and forgotten. We’ll see how to achieve that in this post.

Read more of this post

Getting a result from a parallel task in Java

In this post we saw how to execute a task on a different thread in Java. The examples demonstrated how to start a thread in the background without the main thread waiting for a result. This strategy is called fire-and-forget and is ideal in cases where the task has no return value.

However, that’s not always the case. What if we want to wait for the task to finish and return a result? Welcome to the future… or to the Future with a capital F.

Read more of this post

Running a task on a different thread in Java 8

Occasionally it can be worth putting a task on a different thread so that it doesn’t block the main thread. Examples include a task that analyses heavy files, a task that sends out emails etc. If we put these tasks on a different thread and don’t wait for it to return a result then it’s called the fire-and-forget pattern. We start a new thread and let it run in the background. The task on the different thread is expected to carry out its functions independently of the main thread.

Let’s imagine that the following greetCustomer method is something we want to run on separate thread so that the main thread is not blocked:

Read more of this post

Share data between Tasks using locks in .NET C#

You need to be careful when sharing mutable data across several tasks. If you don’t restrict the access to a shared variable then the tasks will all modify it in an unpredictable way. It’s because you cannot be sure how the tasks will be started and managed by the operating system: it depends on a range of parameters, such as the CPU usage, available memory, etc. If each task is supposed to modify a variable then maybe the first task won’t finish its work before the second task reads the same variable.

Consider the following:

class BankAccount
{
	public int Balance { get; set; }
}

The following code builds a list of tasks that each increase the balance by 1:

BankAccount account = new BankAccount();
List<Task> tasks = new List<Task>();

for (int i = 0; i < 5; i++)
{
	tasks.Add(Task.Factory.StartNew(() =>
	{
		for (int j = 0; j < 1000; j++)
		{
			account.Balance = account.Balance + 1;
		}
	}));
}
Task.WaitAll(tasks.ToArray());
Console.WriteLine(string.Concat("Expected value 5000", ", actual value ",account.Balance));

We expect the final balance to be 5000. Run the code and you will most likely get something less, such as 3856 or 4652. At times you get exactly 5000 but it’s unpredictable.

In such cases you need to identify the volatile critical regions in your code. In this example it’s simple:

account.Balance = account.Balance + 1;

It is the account balance that is modified by each thread so we need to lock it for access so that only one thread can modify it at a certain time. You can take the word “lock” almost literally as we use the lock keyword to do that. We take an object which will act as the synchronisation primitive. The lock object must be visible to all tasks:

object lockObject = new object();

You use the lock keyword as follows:

for (int i = 0; i < 5; i++)
{
	tasks.Add(Task.Factory.StartNew(() =>
	{
		for (int j = 0; j < 1000; j++)
		{
			lock (lockObject)
			{
				account.Balance = account.Balance + 1;
			}
		}
	}));
}

The volatile region of the code is locked using the lock object. The lock is released as soon as the current task has finished working with it.

Run the modified code and you should get the correct result.

View the list of posts on the Task Parallel Library here.

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: