Book Image

Java 7 Concurrency Cookbook

By : Javier Fernández González
Book Image

Java 7 Concurrency Cookbook

By: Javier Fernández González

Overview of this book

<p><undefined:p><undefined:undefined:p>Java remains the global standard for developing various applications and enterprise software, and the launch of Java 7 brings with it exciting new capabilities for concurrent programming by way of the concurrency utilities enhancement. This allows developers to make the most of their applications with parallel task performance. "Java 7 Concurrency Cookbook" covers all elements of the Java concurrency API, providing essential recipes for taking advantage of the exciting new capabilities.<undefined:undefined:br><undefined:undefined:br>On your computer, you can listen to music while you edit a Word document and read your emails, all at once! This is because your operating system allows the concurrency of tasks, much like the Java platform which offers various classes to execute concurrent tasks inside a Java program. "Java 7 Concurrency Cookbook" covers the most important features of the Java concurrency API, with special emphasis on the new capabilities of version 7. <undefined:undefined:br><undefined:undefined:br>With each version, Java increases the available functionality to facilitate development of concurrent programs. This book covers the most important and useful mechanisms included in version 7 of the Java concurrency API, so you will be able to use them directly in your applications.<undefined:undefined:br><undefined:undefined:br>"Java 7 Concurrency Cookbook" includes recipes to enable you to achieve everything from the basic management of threads and tasks, to the new Fork /Join framework, through synchronization mechanisms between tasks, different types of concurrent tasks that Java can execute, data structures that must be used in concurrent applications and the classes of the library that can be customized.<undefined:undefined:br><undefined:undefined:br>With the step-by-step examples in this book you&rsquo;ll be able to apply the most important and useful features of the Java 7 concurrency API.</undefined:undefined:br></undefined:undefined:br></undefined:undefined:br></undefined:undefined:br></undefined:undefined:br></undefined:undefined:br></undefined:undefined:br></undefined:undefined:br></undefined:undefined:p></undefined:p></p>
Table of Contents (15 chapters)
Java 7 Concurrency Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Processing uncontrolled exceptions in a thread


There are two kinds of exceptions in Java:

  • Checked exceptions: These exceptions must be specified in the throws clause of a method or caught inside them. For example, IOException or ClassNotFoundException.

  • Unchecked exceptions: These exceptions don't have to be specified or caught. For example, NumberFormatException.

When a checked exception is thrown inside the run() method of a Thread object, we have to catch and treat them, because the run() method doesn't accept a throws clause. When an unchecked exception is thrown inside the run() method of a Thread object, the default behaviour is to write the stack trace in the console and exit the program.

Fortunately, Java provides us with a mechanism to catch and treat the unchecked exceptions thrown in a Thread object to avoid the program ending.

In this recipe, we will learn this mechanism using an example.

Getting ready

The example of this recipe has been implemented using the Eclipse IDE. If you use Eclipse or other IDE such as NetBeans, open it and create a new Java project.

How to do it...

Follow these steps to implement the example:

  1. First of all, we have to implement a class to treat the unchecked exceptions. This class must implement the UncaughtExceptionHandler interface and implement the uncaughtException() method declared in that interface. In our case, call this class ExceptionHandler and make the method to write information about Exception and Thread that threw it. Following is the code:

    public class ExceptionHandler implements UncaughtExceptionHandler {
      public void uncaughtException(Thread t, Throwable e) {
        System.out.printf("An exception has been captured\n");
        System.out.printf("Thread: %s\n",t.getId());
        System.out.printf("Exception: %s: %s\n",e.getClass().getName(),e.getMessage());
        System.out.printf("Stack Trace: \n");
        e.printStackTrace(System.out);
        System.out.printf("Thread status: %s\n",t.getState());
      }
    }
  2. Now, implement a class that throws an unchecked exception. Call this class Task, specify that it implements the Runnable interface, implement the run() method, and force the exception, for example, try to convert a string value into an int value.

    public class Task implements Runnable {
      @Override
      public void run() {
        int numero=Integer.parseInt("TTT");
      }
    }
  3. Now, implement the main class of the example. Implement a class called Main with a main() method.

    public class Main {
      public static void main(String[] args) {
  4. Create a Task object and Thread to run it. Set the unchecked exception handler using the setUncaughtExceptionHandler() method and start executing Thread.

        Task task=new Task();
        Thread thread=new Thread(task);
        thread.setUncaughtExceptionHandler(new ExceptionHandler());
        thread.start();
        }
    }
  5. Run the example and see the results.

How it works...

In the following screenshot, you can see the results of the execution of the example. The exception is thrown and captured by the handler that writes the information in console about Exception and Thread that threw it. Refer to the following screenshot:

When an exception is thrown in a thread and is not caught (it has to be an unchecked exception), the JVM checks if the thread has an uncaught exception handler set by the corresponding method. If it has, the JVM invokes this method with the Thread object and Exception as arguments.

If the thread has not got an uncaught exception handler, the JVM prints the stack trace in the console and exits the program.

There's more...

The Thread class has another method related to the process of uncaught exceptions. It's the static method setDefaultUncaughtExceptionHandler() that establishes an exception handler for all the Thread objects in the application.

When an uncaught exception is thrown in Thread, the JVM looks for three possible handlers for this exception.

First, it looks for the uncaught exception handler of the Thread objects as we learned in this recipe. If this handler doesn't exist, then the JVM looks for the uncaught exception handler for ThreadGroup of the Thread objects as was explained in the Processing uncontrolled exceptions in a group of threads recipe. If this method doesn't exist, the JVM looks for the default uncaught exception handler as we learned in this recipe.

If none of the handlers exits, the JVM writes the stack trace of the exception in the console and exits the program.

See also

  • The Processing uncontrolled exceptions in a group of threads recipe in Chapter 1, Thread Management