Saturday, 18 February 2017



                                                           
MultiThreaded Programming in Java ( PART - III )



 Suspending , Resuming and Stopping Threads

Suspending a thread is a simple mater. Also Resuming it afterwards is simple matter. Earlier , a program used suspend ( ) and resume ( ) , which are methods defined by thread  , to restart the execution of thread. 

The Thread class can also define a method called stop ( ) that stops a thread. Once a thread has been stopped , it cannot be restarted using resume ( ).


Now , in latest version methods of Java , the suspend ( ) method is deprecated. This was done because suspend ( ) can sometimes cause serious system failures.

If a thread has obtained locks on critical data structure  and if it is suspended at that point , those locks are not relinquished , other threads may be waiting for resources which can lead to deadlock.

The resume ( ) method has also been deprecated  as it cannot be used without suspend ( ) method as counterpart.

The stop ( )  method of thread class has also been deprecated. It was done because this method can sometimes can cause serious system failures.

If thread is writing to a critically important data structure and has completed only part of its changes. If the thread is stopped at that point , that data structure might be left in a corrupted state.

Since we cannot  use suspend ( ) , resume ( ) and stop ( ) methods in threads , there occurs a serious issue to pause , restart and terminate a thread. In the latest java software , the thread must be designed so that the run ( ) method periodically checks to determine whether that thread should suspend , resume or stop its own execution.

This is done by establishing a flag variable that indicates the execution state of thread. 

If the flag is set to "running" , the run ( ) method must continue to let the thread execute.  If the variable is set to "suspend" , the thread must pause. If it is set to "stop" , the thread must terminate.

Ex-  // Suspending and resuming a thread for java.

  class NewThread implements Runnable
   {
       String name ;
        Thread t;
       boolean suspendFlag ;

       NewThread ( String threadname )
      {
           name=threadname ;
           t= new Thread ( this ,name);
           System.out.println (" New Thread : " + t);
            suspendFlag = false ;
              t.start ( );
        }

  public void run ( )
  {
      try 
     {
          for ( int  i=15 ; i>0 ; i++)
         {
              System.out.println ( name + " : " + i ) ;
               Thread.sleep (200);
                synchronized (this)
                 {
                      while (suspendFlag)
                       {
                              wait ( );
                        }
                  }
             }
        }
        catch ( InterruptedException e)
       {
            System.out.println ( name + "interupted. ");
        }
          System.out.println ( name + "exiting. ");
     }

        void mySuspend ( )
       {
               suspendFlag =true ;
        }
   
          synchronized void myresume (  )
         { 
              suspendFlag = false ;
               notify ( );
        }
  }

  class SuspendResume 
 {
         public static void main ( String [] args )
    {
         NewThread ob1 = new NewThread ("one");
         NewThread ob2 = new NewThread ("Two");

        try
         {
                Thread.sleep (1000);
                 ob1.mysuspend ();
                System.out.println ( "Suspending thread one ");
                 Thread.sleep (1000);
                 ob1.myresume( );
                System.out.println ( " Resuming Thread one ");
                 ob2.mysuspend ( );
                System.out.println ( " Suspending thread one " );
                Thread.sleep(1000);
                 ob2.myresume ( );
                System.out.println ( " Resuming thread two " );
           }
         catch ( InterruptedException e)
          {
               System.out.println ( " Main thread Interrupted ") ;
          }
   
      try
       {
            System.out.println (" Waiting for threads to finish " );
            ob1.t.join ( );
            ob2.t.join ( );
       }
       catch ( InterruptedException e)
       {
            System.out.println ( " Main Thread Interrupted " );
       }
    
           System.out.println ( " Main thread exiting " );
    }
}

  Output:

  New Thread : Thread [ one ,5,main ]
  one : 15
  New Thread : Thread [ Two,5,main]
 two : 15
 one : 14
 two : 14
 one : 13
 two : 13
 one : 12
 two : 12
 one : 11
 two : 11
 suspending thread one
 two : 10
 two : 9
 two : 8
 two : 7
 two : 6
Resuming thread one
Suspending thread Two
 one :10
 one : 9 
 one : 8
 one : 7
 one : 6
Resuming thread two
Waiting for threads to finish.
 two : 5
 one : 5
 two : 4
 one : 4
 two : 3
 one : 3
 two : 2
 one : 2
 two : 1
 one : 1
 Two exiting.
 One exiting.
 Main Thread exiting. 

Wednesday, 15 February 2017


 Creating Multiple Threads

A Program can spawn as many threads as it needs.

Ex- 
      //Creating Multiple Threads

    class NewThread implements Runnable
  {
     String name;
Thread t;

       NewThread ( String threadname)
       {
           name=threadname;
           t= new thread (this, name);
           System.out.println( " New Thread : " + t);
           t.thread( ) ;
        }
        
         public void run ( )
        {
            try
              {
                  for( int i=5 ;i>0 ; i--)
                   {
                        System.out.println ( name + " : " + i);
                         Thread.sleep(1000);
                    }
             }
            catch ( InterruptException e)
            {
                System.out.println ( name + " Interrupted ");
            }
          System.out.println (name + " Exiting ." );
       }
  }
        class MultiThreadDemo
       {
            public static void main ( String args [] )
             {
                 new NewThread ( " One");
                 new NewThread ( "Two");
                 new NewThread ( "Three");

                    try
                      {
                          Thread.sleep (10000);
                       }
                    catch ( InterruptedException e)
                     {
                         System.out.println ( " Main Thread Interrupted");
                      }
             System.out.println( " Main Thread Exiting ");
        }
 }
              Output:
            New Thread : Thread [one,5,main]
            New Thread : Thread [two,5,main]
            New Thread : Thread [Three,5,main]
            one : 5
            two : 5
            three : 5
            one : 4
             .
             .
             .
            one : 1
            two : 1
            three : 1
            one exiting
            two exiting 
            three exiting
            Main Thread Exiting

Thread Priorities

Thread priorities are used by thread scheduler to decide when each thread should be allowed to run. Also , Higher priority thread gets more CPU time than lower priority threads. A higher priority thread can preempt the lower priority one.

Threads with equal priority should get equal access to the CPU. Threads that share the same priority should yeild control once in a while . This ensures that all threads have a chance to run under a nonpreemptive operating system.


Synchronization

When 2 or more threads need access to a shared resource , they need some way to ensure that the resource will be used by only 1 thread at a time. The process by which this is achieved is called Synchronization.

Key to synchronization is the concept of the monitor ( also called as semaphore ) . A monitor is an object that is used as a mutually exclusive lock , or mutex. Only 1 thread can own a monitor ata given time.

InterThread Communication

Interprocess communication helps to achieve a more subtle level of control. Apart from dividing the program into discrete and logical units , it also provides the benefit of polling.

Polling is usually implemented by a loop that is used to check some condition repeatedly. Once a condition is true , appropriate action is taken. This wastes CPU time.

To avoid polling , java includes an elegant interprocess communication mechanism via wait ( ) ,  notify ( ) and notifyAll ( ) methods. These methods are implemented as final methods in object , so all classes have them.

These methods are described as :

wait () : Tells the calling thread to give up the monitor and goto sleep until some other thread enters.

notify ( ) : wakes up the first thread that called wait ( ) on the same object.

notifyAll ( ) : wakes up all the threads that called wake ( ) on same object.


Deadlock

Deadlock is a condition which occurs  when 2 threads have a circular dependency on a pair of synchronized objects. Deadlock is difficult error to debug for 2 reasons : 

 - It occurs only rarely , when the 2 threads time slice in just the right away.

 - It may involve more than 2 threads and 2 synchronized objects.


                                                                        By: Knowledge Bits




Monday, 13 February 2017


 Here is the list of Top 10 Whey Isolates Proteins that you should look for while getting Shredded :

1. Optimum Nutrition 100% Whey Gold Standard

                                                      
Optimum Nutrition 100% Whey Gold Standard


24g Protein
5g BCAAs
110 Calories

2.Transparent Labs Protein Series 100% Grass Fed Whey Protein Isolate

                                                         
Transparent Labs Protein Series 100% Grass Fed Whey Protein Isolate

                                       

28g Protein
0g Carbs
112 Calories

3. MuscleTech Phase 8

                                                     
MuscleTech Phase 8
     

26g Protein
5g Glutamine
150 Calories

4. BSN Syntha 6

                                                      
BSN Syntha 6
      

22g Protein
10g Amino Acids
200 Calories

5.  Optimum Nutrition Pro Complex
   
         
                                               
Optimum Nutrition Pro Complex
                          
60g Protein
15.5g BCAAs
270 Calories

6.  Dymatize Iso-100 

                                                       
Dymatize Iso-100
                        

25g Protein
5.5g BCAAs
106 Calories

7. MusclePharm Combat Powder

                                                        
MusclePharm Combat Powder
                  

25g Protein
8g Carbs
140 Calories

8.  Nature’s Best Zero Carb Isopure

                                                      
Nature’s Best Zero Carb Isopure


50g Protein
0g Carbs
220 Calories

9.  CytoSport Muscle Milk

                                                     
CytoSport Muscle Milk
            

32g Protein
12g Carbs
348 Calories

10.  Gaspari Nutrition Myofusion Advanced Protein 

                                                         
Gaspari Nutrition Myofusion Advanced Protein


25g Protein
9g Amino Acids
150 Calories 


                                                                           By: Knowledge Bits

Sunday, 12 February 2017


                                                   
MultiThreaded Programming in Java ( PART - II )


 Synchronization

Since multithreading introduces an asynchronous behaviour to your programs , there must be a way for you to enforce synchronicity when you need it.

In order to prevent conflict between 2 threads we use the monitor. The monitor is a control mechanism first defined by C.A.R Hoare . Monitor can be considered as very small box which can hold only 1 thread.

So , a monitor can be used to protect a shared asset from being manipulated by more than 1 thread at a time.


Messaging

After you divide your program into separate threads , you need to define how they will communicate with each other. Java's provide a clean , low cost way for two or more threads to talk to each other , via calls to predefined methods that all objects have.

Java's messaging system allows a thread to enter a synchronized method on an object and then wait there untill some other thread explicitly notifies it to come out.


The  main Thread

When a java program starts up , one thread begins running immediately. This is the main thread of the program , because it is the one that is executed when your program begins.

It is important :

- It is the thread from which other child threads will be spawned.

- It must be the last thread to finish the execution because it performs the various shutdown actions.

It's general form is :

    static Thread currentThread ()

 // controlling the main thread 
  
   class CurrentThreadDemo
 {
    public static void main ( String [] args )
   {
      Thread t = Thread.currentThread () ;

         System.out.println (" Current thread  :" + t);
          t.setName(" My Thread ");
        System.out.println ( " After name change : " + t);

     try
    {
         for ( int n=5 ; n> 0 ; n--)
         {
             System.out.println(n);
                Thread.sleep(1000);
         }
   }
    catch ( InterruptedException e)
    {
      System.out.println (" Main thread interrupted" );
    }
  }
}
                 Output:
            curent Thread : Thread(main,5,main)
          After name change : Thread ( My Thread,5,main)
          5
          4
          3
          2
          1


Creating Thread

You create a thread by instantiating an object of type Thread. Java defines 2 ways in which this can be accomplished :

  - By Implementing  Runnable interface.
  - By Implementing Thread Class.




Friday, 10 February 2017


                                                     
MultiThreaded Programming in Java ( PART - I )
 

A MultiThreaded program  contains 2 or more parts that can run concurrently. Each part of the program is called as thread and each thread defines a separate path of execution. Thus , it is also called as specialized form of Multitasking.

There are 2 type of  MultiTasking :

- Process  Based
- Thread Based

Process Based : 

 A process  is the program that is executing. Thus , process based multitasking is the feature that allows your computer to run 2 or more programs concurrently. 

In this , a program is the smallest unit of code that can be dispatched by the scheduler.

Thread Based :

In this , a Thread is the smallest unit of the dispatchable code. This means that single program can perform 2 or more tasks simultaneously.

The Java Thread Model

The java runtime system depends on threads for many things and java uses threads to enable the entire environment to be asynchronous. This help reduce in efficiency by preventing the waste of CPU cycles.

In  java thread model , the main loop / polling system is eliminated , which was main component of single thread system and thus made it inefficient.

In java's thread model ,  , 1 thread can  pause  without stopping other parts of your program. When a thread blocks in java program , only the single thread that is blocked pauses , all other threads continue to run.

The threads has 6 states :

- Running  : when is currently running.
- Ready To Run :  When it gets CPU time .
- Suspended  : Temporarily suspends it's activity.
- Resumed : suspended thread picks up from where it was left off.
- Blocked : Waiting for a Resource.
- Terminated   : Halts the Execution. 

Thread Priorities

Java assigns to each thread a priority that determines how that thread should be treated with respect to the others. Thread priorities are integers that specify the relative priority of 1 thread to another.

A thread priority is used  to decide when to switch from 1 running thread to the next. This is called Context Switch. The rules are :

- A thread can voluntarily relinquish control

This is done by explicitly yeilding , sleeping or blocking on pending I/O.

- A thread can be preempted by a higher priority thread

 a lower priority thread that does not yield the processor is simply preempted , no matter what it is doing.


                                                                       By: Knowledge Bits

Thursday, 9 February 2017


 An exception is an abnormal condition that has occurred in a piece of code. It may be refered to as error. 

The java Exception is an object that describes an exceptional condition that has occurred in a piece of code. When an exceptional condition arises , an object representing that exception is caught and thrown in the method that caused it.


The exception can be generated by the java run-time system or they can be manually generated by a code.

In Java , the exception is managed by 5 keywords :

   - try
   - catch
   - throw
   - throws
   - finally

The program statements that you want to check are contained within the try block . If an exception occurs within the try block ,it is thrown.

Your code can catch the exception using catch and handle it in some rational manner. To manually throw an exception , use throw.
Any exception that is thrown out of the must be specified by a throws clause.

Any code that must be executed before a method returns is put in a finally block.

It's general form is :

   try {
  //block of code to monitor for errors
   }
 catch ( ExceptionType 1 e)
  {
   //Exception handler
  }
.....
  catch ( ExceptionType N e)
   {
    //Exception handler
    }
   finally
  {
  //Code that must be executed
   }

 The exception that is not caught by your program will ultimately be processed by the default handler. The default handler displays a string describing the exception , prints a stack trace from the point at which the exception ocurred and terminates the program.

Ex-    ( Try and Catch )

   class TryCatchDemo
   {
    public static void main ( String [] args )
      {
             int d,a;
           try
            {
                       d=0;
                       a=42/d;
                  System.out.println (" This will not be printed");
             }
           catch ( ArithmeticException e)
            {
              System.out.println (" Caught " + e);
             }
             System.out.println (" After catch statement");
        }
  }
                                                Output:
                                             Division by Zero
                                             After Catch Statement

Ex-    ( Multiple catch clauses)

 class MultipleCatch
 {
      public static void main ( String [] args )
    {
           try
            {
                int a=args.length;
              System.out.println( "a=" +a);
               int b =42/a;
               int c[] = {2};
                c[42]=99;
             }
            catch ( ArithmeticException e)
             {
                System.out.println (" Divide by 0 " + e);
              }
            catch ( ArrayIndexOutOfBoundsException e)
             {
                 System.out.println( " Array index oob :" + e);
              }
           System.out.println ( " After try/catch blocks ");  
       }
 }


 Ex-   (Nested Try )

   class NestedTry
  {
     public static void main ( String [] args )
     {
          try
          {
              int a= args.length;
              int b = 42/a;
              System.out.println ( "a = " + a);
                   
                      try
                        {
                                 if (a==1)
                                    a=a/(a-a);

                               if ( a==2)
                             {
                                   int c[] = {1};
                                     c[42]=99;
                             }
                       }
                     catch (ArrayIndexOutOfBoundsException e)
                      {
                       System.out.println(" Array index out of bounds" +e);
                      }
                  }
              catch (ArithmeticException e)
               {
                   System.out.println (" Divide by 0 : " + e);
                }
        }
 }


  Ex-       ( Throw )

    class throwdemo
      {
           static void demo ()
          {
                  try
                  {
                     throw new NullPointerException("d");
                   }
                  catch( NullPointerException e)
                  {
                      System.out.println (" caught inside ");
                        throw e;
                   }
           }
      public static void main ( String [] args )
      {
            try
            {
                  demo ( );
            }
            catch( NullPointerException e)
           {
             System.out.println(" Recaught :" + e);
           }
      }
 }


   Ex-    ( Throws)

    class ThrowsDemo
   {
         static void throwOne () throws IllegalAccessException
        {  
            System.out.println(" Inside throw one");
           throw new IllegalAccessException ("demo");
        }
        public static void main ( String [] args )
      {
        try
        {
           throwOne( );
        }
        catch ( IllegalAccessException e)
       {
          System.out.println ( "Caught " +e);
       }
   }
}

Ex-   ( Finally )

  class FinallyDemo
   {
    public static void main ( String [] args )
      {
             int d,a;
           try
            {
                       d=0;
                       a=42/d;
                  System.out.println (" This will not be printed");
             }
           catch ( ArithmeticException e)
            {
              System.out.println (" Caught " + e);
             }
            finally
           {
             System.out.println (" After catch statement");
          }   
     }
}

                                                                      By: Knowledge Bits

Wednesday, 8 February 2017


                                                       
Packages And Interfaces
                                     

Packages

Packages are the containers for classes that are used to keep the class name space compartmentalized. Packages are stored in a hierarchical manner and are explicitly imported into new class definitions.

To create a package , simply include a package command as the first statement in a java source file. It's general form is:

  package pkg;

          here pkg is the name of package.

Ex-

   //Simple package program
package MyPack;

class balance 
{
    String name;
     double bal;

   Balance ( String n , double b)
{
    name=n;
     bal=b;
 }
 void show() 
{
  if(bal<0)
     System.out.print("===>");
     System.out.println(name + " Rs" + bal);
  }
}
class AccountBalance
{
     public static void main ( String [] args )
   {
       Balance curr [] = new Balance [3];
       curr [0] = new Balance (" ABC " , 123.334);
       curr [1] = new Balance (" PQR " , 1243.4);
       curr [2] = new Balance (" XYZ " , 44567.564);

    for( int i=0 ; i<3 ; i++)
   {
         current[i].show();
    }
}

Interfaces

Using the keyword interface , you can fully abstract a class's interface from its implementation. Interface specifies , What a class must do , but not how it does it.

Interface are syntactically similar to classes , but they lack  instance variables , and their methods are declared without any body.Once defined any number of classes can implement an interface. Also , one class can implement any number of interfaces.

It's general form is :

       access_modifier  interface name 
{
        return_type   method_name1 ( );
        return_type   method_name2 ( );
         type final varname1 = value ;
          type final varname2 = value ;
          .
          .
          .
          return_type   method_nameN ( );
          type final varnameN = value ;
 }

  Here , access_specifier is either public or not used , name is the name of interface , 


Ex-
   
          class client implements callback
{
            public void callback ( int p)
    {
        System.out.println (" Callback called with " + p);
     }
}
        
                                                                       By: Knowledge Bits

Video of the Day

Contact us

Name

Email *

Message *