Sunday, May 5, 2013

Java Concurrency Part 2

Here it is the part 2 from my original post: java-concurrency part-1


Thread's priority

All threads have a priority value between 1 and 10. In most cases, the running thread will have the same priority than the highest priority of the threads in the pool.
If some threads have the same priority, it is the scheduler who decides which thread executes.

By default a thread gets its priority from the thread of execution who created it, but it can be changed through the setPriority(int) method, this method can throw an IllegalArgumentException if the value set is not between 1 and 10.

The static yield() method of the Thread class indicates to the JVM that the current thread can leave the CPU and go to the runnable state allowing other threads with the same or higher priority to run. The JVM does not guarantee that this behavior.

Thread sleep

The static sleep(long) method of the Thread class causes the current thread to stop executing for at least the specified sleep duration in milliseconds indicated by the parameter.
When sleeping time ends the JVM assigns CPU time to the sleeping thread, it continues in the next instruction after the sleep() method call.

 Example:

                     public class Calculator extends Thread {
                    public void run() {
                 System.out.println(“Thread running:” + this.getName() + “, started at:” +
                                              Calendar.getInstance().getTimeInMillis());
                               try {
                                   Thread.sleep(5000);
                               } catch (InterruptedException e) {
                                  e.printStackTrace();
                               }
                 System.out.println(“Thread running:” + this.getName() + “, finished at:” +
                                                 Calendar.getInstance().getTimeInMillis());
                    }
               }

The messages in the console should have a time difference of at least of 5 seconds.

Exceptions

The InterruptedException is thrown be some methods related with the java concurrency API, to indicate that the thread has been interrupted.

If you don't know what is an checked or unchecked exception are, then go to this link http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html

Checked exceptions thrown inside the run() method of a Thread Object should be catch and treated, because the run() method in the Runnable interface doesn't declare any throws clause.

Unchecked exceptions thrown inside the run() method of a Thread Object don't require to catch them and must of the time cause the program to exit. For this type of exceptions Java provides a way to catch and treat the unchecked exceptions thrown in a Thread object to avoid the program ending.



 The steps to implement this are:
  1. Create a class that implements Thread.UncaughtExceptionHandler.
  2. Set the exception handler to the Thread Object.


Example
                  public class ExceptionHandler implements UncaughtExceptionHandler {

                       public void uncaughtException(Thread t, Throwable e) {
                            System.out.println("An exception has been captured");
                            e.printStackTrace(System.out);
                            System.out.println("Thread status: " + t.getState());
                       }
                   }


                   public class Calculator implements Thread {
                         public void run() {
                              throw new RuntimeException(“Exception thrown”);
                         }
                   }

                   ..........
                   Calculator calculator = new Calculator();
                   calculator.setUncaughtExceptionHandler(new ExceptionHandler());
                   calculator.start();
                   ..........

The console should print the messages from the exception handler.

Thread class has another method for handle uncaught exceptions, it is the static method setDefaultUncaughtExceptionHandler(), this methods sets an exception handler for all Threads in the application.

Factory of threads

The factory pattern is a creational pattern whose mission is to create objects. This pattern provide some
advantages such as ease to change the way objects are created, limit the creation of resources, and so on.

The interface java.util.concurrent.ThreadFactory provides a way to implement a Thread object factory. It only has the newThread() method and it receives a Runnable object as a parameter and returns a Thread object.

Example

                     public class Factory implements ThreadFactory {
                           private int counter = 1;

                           public Thread newThread(Runnable r) {
                                Thread t=new Thread(r, "Thread: " +counter);
                                counter++;
                                return t;
                           }
                      }

                      public class Calculator implements Runnable {
                           public void run() {
                                .....
                           }
                      }

                      ....
                     Factory factory=new Factory();
                     Calculator calculator = new Calculator ();
                     for (int i=0; i<10; i++){
                          Thread thread=factory.newThread(calculator);
                           thread.start();
                     }
                     .....

At the end of the for loop 10 threads have been created and started.


Go to part 3


No comments:

Post a Comment