JavaHandling Concurrency in Java

Handling Concurrency in Java

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Concurrency is the ability of the operating system to execute two or more tasks in parallel. Concurrency handling allows you to detect and resolve conflicts that can occur when there are concurrent requests to the same resource at a given point in time. Threads share the resources of a process that includes memory resources, process data and open files. This, though it helps to make your application more efficient, might cause issues at runtime due to concurrent access to the same resource. This article explores the Java Concurrency Utilities – high-level concurrency types that facilitate threading and task management on multicore systems. The article provides plenty of real life code examples to illustrate the concepts.

The Java Concurrency Utilities Framework

Multithreading may be defined as the ability of the operating system to have multiple threads in memory with one of them in the execution state. Hence, if you have n threads in a system, then one of those threads would be in the execution state and the other n – 1 threads would be in the ready or runnable state. Multi-threading if used judiciously, helps reduce the development and maintenance costs and improves the responsiveness and overall performance of the application. Handling concurrency is a concern when you have one or more threads accessing the same resource. The Java Executor Framework, an abstract layer over the underlying Java threading framework, was introduced in Java 1.5 and is contained in the Java Concurrency Package.

The Java Programming Language provides support for handling thread safety and concurrency issues. However, the keywords and methods synchronized, volatile, wait(), notify(), and notifyAll() in Java are difficult to use. Most importantly, you need to depend on the synchronized keyword in Java to provide thread safety. In essence, Java’s threading framework is too low level. The Java Concurrency Utilities framework provides a standardized, easy to use, high performance and robust library to work with concurrency techniques in your Java applications.

The Java Concurrency Utilities framework contains the following main packages:

  • java.util.concurrent
  • java.util.concurrent.atomic
  • java.util.concurrent.locks

The Java Concurrency Utilities framework in the java.util.concurrent package is a library that contains thread-safe types that are used to handle concurrency in Java applications. These types in the Java Concurrency Utilities framework are in turn organized into the following frameworks:

  • Executor framework
  • Synchronizer framework
  • Concurrent collections
  • Locks
  • Atomic variables
  • Fork/Join

The important classes and interfaces in the Java Concurrency framework include:

  • Executors
  • Thread Factory
  • Futures
  • Queues
  • Conditions
  • Synchronizers
  • Concurrent Collections
  • Atomic Variables
  • Locks

An executor is just another object that executes runnable tasks. The Executor framework is based on the Executor interface and decouples task submission from task execution. The Executor framework provides support for an ExecutorService interface. This interface in turn extends Executor. The following is the list of the methods of the ExecutorService.

  • boolean awaitTermination(long timeout, TimeUnit unit)
  • boolean isShutdown()
  • void shutdown()
  • <T> Future<T> submit(Callable<T> task)
  • Future<?> submit(Runnable task)

The following code snippet illustrates how you can work with this framework.

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
class MyServer
{
static Executor threadPool = Executors.newFixedThreadPool(10);
public static void main(String[] args) throws IOException
{
ServerSocket serverSocketObj = new ServerSocket(9000);
while (true)
{
final Socket socketObj = serverSocketObj.accept();
Runnable runnable = new Runnable()
{
public void run()
{
SomeTask(socketObj);
}
};
threadPool.execute(runnable);
}
}
static void SomeTask(Socket socket)
{
//Some code
}
}

The following code shows the complete implementation of a program in which we create two tasks using the Java Concurrency Utilities framework and execute them concurrently.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ThreadDemo {
private static ExecutorService executorServiceObj = null;
private static volatile Future taskOneResults = null;
private static volatile Future taskTwoResults = null;
public static void main(String[] args) {
executor = Executors.newFixedThreadPool(1);
while (true)
{
try
{
ExecuteTasks();
Thread.sleep(5000);
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
}
}
}
private static void ExecuteTasks() throws Exception
{
if (taskOneResults == null)
{
taskOneResults = executorServiceObj.submit(new MyTask ());
}
if (taskTwoResults == null)
{
taskTwoResults = executorServiceObj.submit(new MyTask ());
}
}
}
class MyTask implements Runnable {
public void run() {
while (true)
{
System.out.println("Executing task…");
try
{
Thread.sleep(5000);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
}

References

http://en.wikipedia.org/wiki/Java_concurrency

Summary

The Java Concurrency Framework comprises of a collection of thread-safe and robust services that enable you to develop applications that can leverage the advantages of concurrent programming. The Java Concurrency Utilities framework provides a high-level, thread-safe, high performant alternative to Java’s low-level threading capabilities and is organized into several other frameworks namely, java.util.concurrent, java.util.concurrent.atomic and java.util.concurrent.locks. In this article we examined concurrency handling concepts and explored the Java Concurrency Utilities framework. We will explore more on this framework in future articles in this series. Happy reading!

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories