Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Wednesday, 16 November 2016

Catching Child thread class exceptions in Main thread class and vice-versa in java

I came across a situation where we need to handle child thread class exceptions in main  thread class. Means which exception child class is throwing that to be handled by Main class.

Hope Most of the experience Java guys know this. This question normally asked in interview questions for experience people. I too came across this same question in one of my interview. That’s why I am sharing this program in my blog. Hope those who visit my page get benefit of it.

I have written two programs for this using.

  • UncaughtExceptionHandler
  • Executors Framework


Using UncaughtExceptionHandler: 

In this program I have used java 8 Lambda expression. If you not familiar with Java 8, you can comment java8 line and uncomment the java7 code.


import java.lang.Thread.UncaughtExceptionHandler;

/**
 * @author Bipin
 * This demonstrates how Main thread can see and print the exceptions generated by child thread
 *
 */
public class ChildThreadThrowingException {
       public static void main(String... args) {
            
             System.out.println("Main Thread");
             MyThread t = new MyThread();
            
// functional interface
   /*
   UncaughtExceptionHandler h = new UncaughtExceptionHandler()                                         {                          
              
                    @Override
                    public void uncaughtException(Thread thread, Throwable throwable) {
                           System.out.println(throwable);
                          
                    }
             };
             */
            
             
             // Using Java 8
      //UncaughtExceptionHandler h = (Thread thread, Throwable throwable) -> System.out.println(throwable);
            
//More advantage of Java 8             
       UncaughtExceptionHandler h = (thread, throwable) -> System.out.println(throwable);
            
             t.start();
             t.setUncaughtExceptionHandler(h);
            
       }
}

class MyThread extends Thread {
      
       private int x;

       public void run() {
             System.out.println("Child Thread");
             try {
                    x = 9/0;
                    System.out.println(x);
             }
             catch(ArithmeticException e) {
                    throw new ArithmeticException("Divide By Zero");
             }
            
       }
}

o/p:
Main Thread
Child Thread
java.lang.ArithmeticException: Divide By Zero


Using Executors Framework

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/*
 * This class is going to use ExcecutorService and Future to handle the Exception
 */
public class MyExecutorService {

      
       public static void main(String[] args) {
            
             System.out.println("Main Thread");
            
             //Creates a thread pool that creates new threads as needed,
             //but will reuse previously constructed threads when they are available.
             ExecutorService executor = Executors.newCachedThreadPool();
            
             //Get the return object and used get() method that can wait for
             //the Callable to finish and then return the result.
             Future<Integer> future = executor.submit(new Callable<Integer>() {
                    /*                 
                     * Call method can either return a value or exception
                     */
                    @Override
                    public Integer call() throws Exception {
                          
                           Random random =  new Random();
                           int duration = random.nextInt(4000);
                          
                           if(duration > 2000) {
                                 throw new IOException("Sleep for "+duration+" miliseconds. Too much to sleep");
                           }
                          
                           System.out.println("Child Thread Starting");
                          
                           Thread.sleep(duration);
                          
                           System.out.println("Child Thread finished");
                          
                           return duration;
                    }
             });
            
             executor.shutdown();
            
             try {
                   
                    //Print the future result
                    System.out.println(future.get());
                   
             } catch (InterruptedException | ExecutionException e) {
                   
                    //Print the exception message that is set in call()
                    //System.out.println(e.getCause().getMessage()); //o/p: Sleep for 2766 miliseconds. Too much to sleep
                   
                    System.out.println(e.getMessage()); //o/p: java.io.IOException: Sleep for 2173 miliseconds. Too much to sleep
             }
       }

}


The End. Happy Codding. J

Thanks

Bipin

Tuesday, 3 July 2012

How static block works in Java


Static block and its description in Java

Static Block in Java:

In java, static is a keyword. All static stuffs(static variable, static method) belong to the class and not to the object(instance). Before going to static block, let's discuss about some static stuffs.


Static variables are basically class variables. When you define a static variable for your class implementation, there will be only one copy of the variable for the class rather than one for each instance of the class. They can be accessed without creating an instance of the class.

Static methods also called class methods and can be accessed without creating an instance of the class and like static variables, static methods will be accessed without instantiating the class .

Ex:
public class Test
    {
    static int foo = 12345;        
     static void TestMethod()
                {
               foo++;
                        }
 public static void main(String arge[])
 {
 System.out.println(foo);          //directly accessed  o/p:12345
 TestMethod();                    // directly accessed
 System.out.println(foo);        // o/p : 12346
 }
    
    }

Static blocks:

  1. Static blocks are also called Static initialization blocks .
  2. A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword.
    Ex :

    static {          // whatever code is needed for initialization goes here        }
  3. A class can have more then one static block in the class body.The run time system guarantees that static initialization blocks are called in the order that they appear in the source code.
  4. If you’re referring some static variables/methods from the static blocks, these statements will be executed after the class is loaded into JVM same as above i.e., now the static variables/methods referred and the static block both will be executed.

Ex:
public class Test
{
static int num;
static int res;
     static
            {
             num = 10;
             res = 12;
             System.out.println("I am static block, I am called first.");
             System.out.println("Result : "+(num*res));                              // o/p : 120
             past();                                                                                   // o/p : Method Block
     }
public static void main(String args[])
          {
          System.out.println("I am main() method, executed after static block.");
          System.out.println("Result : "+(num*res)); // o/p : 120
          }
static void past()
          {
          System.out.println("Method Block");
         }
}


O/P:

I am static block, I am called first.
Result : 120
Method Block
I am main() method, executed after static block.
Result : 120

 5. Static block can access instance variables (non-static variables) and instance methods by         creating an object of the class.

Ex :
public class Test
{
int num;
int res;
static Test T1;
    static
          {
          T1=new Test();
          T1.num = 10;
          T1.res = 12;
          System.out.println("I am static block, I am called first.");
          System.out.println("Result : "+(T1.num*T1.res));                      // o/p : 120
          T1.past();                          // call to concrete method ,   o/p : Method Block
  }

public static void main(String args[])
{
System.out.println("I am main() method, executed after static block.");
}
void past()
    {
     System.out.println("Method Block");
    }
}


O/p :
I am static block, I am called first.
Result : 120
Method Block
I am main() method, executed after static block.

Advantages of static blocks

  • If you’re loading drivers and other items into the namespace. (for instance Class.forName(”org.h2.Driver”)).
  • Initialize your static members at once ,as static block run once in the program execution.
  • Limitations for static blocks
  • You cannot throw Checked Exceptions.
  • “this” keyword can not be used since there is no instance.
  • You shouldn’t try to access super since there is no such a thing for static blocks.
  • You should not return anything from this block.


Non-Static Block/ constructor block

  • if we remove static keyword from static block/ initialization block, then it said to be non-Static block / constructor block.
  • This block is executed when the class is instantiated.
  • How many time your class get instantiated, constructor block/ non-Static block will called each time. That means constructor block will be copied into each constructor of the class.


Here is an Example :

public class NonStaticBlock{
{
System.out.println("First Non Static block");
}

public NonStaticBlock(){
System.out.println("This is no parameter constructor");
}

public NonStaticBlock(String param1){
System.out.println("This is single parameter constructor");
}

public NonStaticBlock(String param1, String param2){
System.out.println("This is two parameters constructor");
}

{
System.out.println("Second Non Static block");
}

public static void main(String[] args){
NonStaticBlock nonStaticEx = new NonStaticBlock();
NonStaticBlock nonStaticEx1 = new NonStaticBlock("java");
NonStaticBlock nonStaticEx2 = new NonStaticBlock("java", "oracle");
}
}

O/P will be like this:
First Non Static block                                 // coming from first constructor block
Second Non Static block                          // coming from second constructor block
This is no parameter constructor              // First instance created & constructor called
First Non Static block
Second Non Static block
This is single parameter constructor
First Non Static block
Second Non Static block
This is two parameters constructor

Tuesday, 17 April 2012

Few OCJP/SCJP Questions and Answers


1. public class LocalTime {
public static void main(String [] args) {
int second;
int min; // second & min only declared but not initialized
System.out.println("Welcome");
second = 180; // Initialize the variable
System.out.println("Minute " + min);
}
}

Ans : Code fails in compilation .Local variable should be initialize before they used in the method/block. Here “min” variable is no where used in the program..

2. public class LocalTest {
public static void main(String [] args) {
int a;
if (args[0] != null) { // assume you know this will
// always be true

a = 7; // compiler can't tell that this
//  statement will run
}
int b = a; //Compiler will choke here
}
}
Ans: Compilation Error. The variable “a” is only initialize in the loop. When JVM comes from the loop, it can not find the value of “a” .

3. class Foo {
static int size = 7;
static void changeIt(int size) {
size = size + 100;
System.out.println("size in changeIt is " + size);
}
public static void main (String [] args) {
Foo f = new Foo();
System.out.println("size = " + size);
changeIt(size);
System.out.println("size after changeIt is " + size);
}
}
o/p :
size = 7
size in changeIt is 107
size after changeIt is 7

4. class TestWrapper {
public static void main(String args[]) {
Integer i1 = 1000;
Integer i2 = 1000;
if(i1 != i2) System.out.println("different objects");
if(i1.equals(i2)) System.out.println("meaningfully equal");
}
}

o/p:
different objects
meaningfully equal

5 .
class TestWrapper {
public static void main(String args[]) {
Integer i2 = 20;
Integer i3 = 20;
if(i2 == i3) System.out.println("same object");
if(i2.equals(i3)) System.out.println("meaningfully equal");
}
}

o/p :
same object
meaningfully equal

NB :For Short & Integer range from -128 to 127. When == is used to compare a primitive to a wrapper, the wrapper will be unwrapped and the comparison will be primitive to primitive.

6. class Boxing {
static Integer x;
public static void main(String [] args) {
doStuff(x);
}
static void doStuff(int z) {
int z2 = 5;
System.out.println(z2 + z);
} }

0/p: It will throw NullPointerException at Runtime bacause when JVM tries to invoke dostuff(x) method, x does not have the value to outbox.

NB : wrapper reference variables can be null. You have to take care for code that appears to be doing safe primitive operations, but that could throw a NullPointerException:


7. class LongTest {
static void go(int x) { System.out.print("int "); }
static void go(long x) { System.out.print("long "); }
static void go(double x) { System.out.print("double "); }
public static void main(String [] args) {
byte b = 5;
short s = 5;
long l = 5;
float f = 5.0f;
go(b);
go(s);
go(l);
go(f);
}
}
Which produces the output:
int int long double

8. class Dog {
public static void main(String [] args) {
Dog d = new Dog();
d.test(new Long(5)); // can't widen an Integer
// to a Long
}
void test(Double x) { }
}


O/P :  Compilation Fails.
Wrapper class can not widen with one another.



9. class TryWiden {
static void go(Object o) {
Integer b2 = (Integer) o; // ok - it's a Integer object
System.out.println(b2);
}
public static void main(String [] args) {
Integer b = 10;
go(b); // can this integer turn into an Object ?
}
}

o/p: 10

Since Object is the parent class of all wrapper classes(here Byte),so it can widen to Object.

10.
class MixerTest {
MixerTest() { }
MixerTest( MixerTest m) { m1 = m; }
MixerTest m1;
public static void main(String[] args) {
MixerTest m2 = new MixerTest();
MixerTest m3 = new MixerTest(m2); m3.go();
MixerTest m4 = m3.m1; m4.go();
MixerTest m5 = m2.m1; m5.go();
}
void go() { System.out.print("hi "); }
}

what will be the o/p ?

o/p : hi hi, followed by an exception
Because m2 object’s m1 instance variable is never initialized, so when m5 tries to use it a NullPointerException is thrown


11. class Bird {
{ System.out.print("b1 "); }
public Bird() { System.out.print("b2 "); }
}
class Raptor extends Bird {
static { System.out.print("r1 "); }
public Raptor() { System.out.print("r2 "); }
{ System.out.print("r3 "); }
static { System.out.print("r4 "); }
}
class Hawk extends Raptor {
public static void main(String[] args) {
System.out.print("pre ");
new Hawk();
System.out.println("hawk ");
}
}

o/p : r1 r4 pre b1 b2 r3 r2 hawk
Static init blocks are executed at class loading time, instance init blocks run
right after the call to super() in a constructor. When multiple init blocks of a single type occur in a class, they run in order, from the top down

12. public class Make {
static int make = 7;
public static void main(String[] args) {
new Make().go(make);
System.out.print(" " + make);
}
void go(int make) {
make++;
for(int make = 3; ouch < 6; ouch++)
;
System.out.print(" " + make);
}
}

o/p : Compilation fails because the variable “make” is declare again in for loop

13. class Dozens {
int[] dz = {1,2,3,4,5,6,7,8,9,10,11,12};
}
public class Mango{
public static void main(String[] args) {
Dozens [] da = new Dozens[3];
da[0] = new Dozens();
Dozens d = new Dozens();
da[1] = d;
d = null;
da[1] = null;
// do stuff
}
}

question : How many objects this program will create & how many are eligible for garbage collection ?

Ans : 5 objects are created & 2 objects are eligible for Garbage Collection