Skip to main content

Posts

Showing posts from 2008

Thread Communication

thread communication deals the problem that if one thread leaves the monitor then how it will tell to the waiting thread that it is now free to get the monitor. java provide interprocess communication machenism through wait() ,notify() and notifyAll() methods. these method are implemented in the object class as final. notify() It called by the monitor owner thread to wakes up a single thread that is waiting for this monitor object. If more then one, threads are waiting for this monitor then one of them is chosen to be awakened. The choice is arbitrary. notifyAll() It called by the monitor owner thread to wakes up multiple threads waiting for this monitor object. wait() Causes current thread to wait until another thread invokes the notify () method or the notifyAll() method for this object. It throws InterruptedException wait(long timeout)                Causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, o

Java Annotations

Self-Descriptive Coding in java. Java has introduced the feature called annotation through which elements of a program can be marked to contain some Meta data. This Meta data may be available at compile time or at running time. Now it is possible to provide some information for methods, fields, classes etc. that will be available at processing time. You can annotate your method telling to calling method how to call your method. You can annotate your class to tell something to class loader how to cerate the object of class and for what the object should be used. You can declare fields in you class those may be annotated to get their value from specified source. New version of java and j2ee has been updated to use annotations. Like EJB, webs services, JPA(java persistence API) etc. New version EJB3.x has been simplified to create the EJB without using any XML file. Because the information required to EJB container are provided by the annotation. EJB programmer annotates his class to prov

Thread Synchronization using synchronized blocks

In the previous example the Shared class provides synchronized method for threads. Threads do nothing so if share class removes the synchronized then thread object will not be able to access the print method synchronously.             There is second mechanism by which the thread can provided the synchronization to the any object or block. class  MyThread1  extends   Thread {         Shared s;     MyThread1(Shared s)     {          this .s = s;     }          public   void  run()     {              synchronized (s)         {             s.print();         }     } } class  MyThread2  extends   Thread {         Shared s;     MyThread2(Shared s)     {          this .s = s;     }          public   void  run()     {              synchronized (s)         {             s.print();         }     } } class  syn {      public   static   void  main( String  ar[])     {         Shared obj = new  Shared();         MyThread1 t1 = new  MyThread1(obj);         MyT

Thread Synchronization

The mechanism to accomplish the mutual access of shared resource for two or more thread is referred as the synchronization .when two or more thread access single resource then it is ensured that only one thread should access it at a time. The core concept of synchronization is the monitor. Only one thread can get the access to monitor at a time or we can say only one thread can enter in the monitor at a time. If one thread using the shared resource than it is said to be in the monitor and it acquires the lock on the monitor so no anther thread has the permission to access the shared recourse. When first thread finishes its execution then it release the lock from the monitor and frees the monitor to use by another thread. In the java all the object have their implicit monitor. So it is easy to synchronize any object or any method of object. There are two ways in which execution of code can be synchronized: ·          synchronized methods ·          synchronized blocks synchronized met

Thread priority

Thread priorities are integer values between 1 and 10 used by the thread scheduler to assign the CPU time for the thread for execute their task. When many threads are executed by the thread scheduler, then the thread scheduler uses the priority associated with thread to decide that how much CPU time should be assigned for particular thread. The thread having the higher priority will execute fast then lower priority because the CPU time assigned to higher priority thread is more then lower priority thread. Some constants are defined in the thread class for specify the priority values and they can be used to assign the relative priorities among the threads. Those are below with their access specifier and access modifier. public static final int MAX_PRIORITY 10 public static final int MIN_PRIORITY 1 public static final int NORM_PRIORITY 5 The execution of multiple threads on a single CPU, in some order, is called scheduling. The Java platform suppor

Joining the threads

If you want that one thread should waits until another thread return from its running process or it die You can do it by using the join() method. If join method is called then the execution stops on that line of code until the thread on which join() called is died . //join //Author @ Hemraj class  MyThread  extends   Thread {      String  msg;     MyThread( String  msg)     {          this .msg = msg;     }      public   void  run()     {          for ( int  i = 0;i < 10;i ++ )         {                  try             {                 sleep(500);             } catch ( InterruptedException  e){}              System .out.println(i + msg);         }     }  } class  MyThrea {      public   static   void  main( String  ar[])     {          MyThread t1 = new  MyThread( "this is t1" );         t1.start();          for ( int  i = 0;i < 10;i ++ )         {                  try             {                  Thread .sleep(500);                 

Checking the thread’s life (isAlive())

To check whether a particular thread is in live state or not, at any time we use isAlive() method. This method returns true if the thread for which it called is in the living state and it returns false if the thread is not alive. //isAlive  class  MyThread  extends   Thread {      public   void  run()     {          for ( int  i = 0;i < 10;i ++ )         {                  try             {                 sleep(500);             } catch ( InterruptedException  e){}         }     }  } class  MyThreadTest {      public   static   void  main( String  ar[])     {          System .out.println( "Start main" );         MyThread t1 = new  MyThread();         t1.start();          for ( int  i = 0;i < 12;i ++ )         {                  try             {                  Thread .sleep(1000);             } catch ( InterruptedException  e){}              if (t1.isAlive())                  System .out.println( "t1 is Alive" );            

Basic Thread’s States

Life cycle of the thread is valuable in the large multithreading application. State of a thread specifies the current activities of the thread at any movement. There are four basic state of the thread. 1.      New – when the object of the class that representing a thread after creating the object, is created then before call the start method the thread can’t run. So it is called new state of the thread or in other words we can say that the thread is said to be in new state. It means the thread has been created and it is ready to run. 2.      Runnable -- Thread exists in several states. A thread that has been just created is in the new state. The thread remains in this state until the thread’s start method is called. This causes the thread to enter the runnable (ready) state when the system assigns a processor to the thread Running – A thread is said to be in the running state if it is executing instructions. The instructions are placed in the run method and when the ru

Thread using extending Thread class

Extending the Thread Class The thread class can be extended to create the thread. A typical procedure for doing this is as follows 1.       A class extending the Thread class overrides the run() method from the Thread class to define the code executed by the thread. 2.       This subclass may call a Thread constructor explicitly in its constructors to initialize the thread, using the super() call. 3.       The start() method inherited from the Thread class is invoked on the object of the class to make the thread eligible for running. c lass  A  extends   Thread {      public   void   run (){          say () ;      }      public   void   say (){          for ( int  i = 0 ;i < 10 ;i ++ ){              try { Thread . sleep ( 500 ) ; } catch ( Exception  e ){}              System .out. println ( "Hello " + i + " times" ) ;          }      } } class  B  extends   Thread {      public   void   run (){          say () ;      }      public   void

Thread Creation using Runnable interface

In java programming there are something predefined which is used to create a thread. The thread in java represent by the Object of your class which has the Thread property. So when you create a thread you have to just put some extended properties in your class due to which the behavior of Object of your class is like the thread. There are two ways to create a thread. First is , Implements Runnable interface in to your class, and defined run method declared by it Second is Extends Thread class in to your class and override the run method. Runnable interface Runnable interface comes from java.lang package. Runnable interface has only one method declaired as follow public interface Runnable {      public void run(); } So to make a thread using the Runnable interface you have to define the run method. The run method is necessary to be thread of a normal class. A thread, which is created based on an object that implements the Runnable interface, will execute t