Monday 29 August 2016

OOPs Concepts

A methodology or paradigm to design a program using classes and objects.

Object Oriented programming is a programming methodology that is associated with the concept of Class.

Objects and various other concepts revovling around these like Inheritance, Polymorphism, Abstraction, Encapsulation etc.

Abstraction
Hiding internal details and showing functionality is known as abstraction. Abstract class and interface can be used to achieve abstraction.
Example: watching TV, we don't know the internal processing.

Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
Example: capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.

Advantage of OOPs over Procedure-oriented programming language
1)OOPs makes development and maintenance easier where as it is not easy to manage the projects if code grows as project size grows.

2)OOPs provides data hiding whereas in Procedure-oriented programming language a global data can be accessed from anywhere.

3)OOPs provides ability to simulate real-world event much more effectively.

Thursday 25 August 2016

How to ensure that the Parent thread will die after the Child thread?

In below given example, the Parent thread dies before the Child thread.
classChildThread1 extends Thread {
     @Override
     public void run() {
           try {
                System.out.println("Child thread start");
                Thread th = Thread.currentThread();
               
                if("Child Thread".equals(th.getName())) {
                     Thread.sleep(1000);
                }
               
                System.out.println("Child thread closed");
               
           } catch(Exception e) {
                System.out.println("exception is" + e);
           }
     }
}

public classCloseChildThreadTest {
    public static void main(String args[]) throws InterruptedException {
    System.out.println("Main thread start");
    ChildThread1 cThread = new ChildThread1();
   
        cThread.setName("Child Thread");
        cThread.start();
        System.out.println("Main thread closed");
    }
}
Output:
Main thread start
Main thread closed
Child thread start
Child thread closed

Ensure the parent dies after the Child thread?

1. Using join() method
classChildThread1 extends Thread {
     @Override
     public void run() {
           try {
                System.out.println("Child thread start");
                Thread th = Thread.currentThread();
               
                if("Child Thread".equals(th.getName())) {
                     Thread.sleep(1000);
                }
               
                System.out.println("Child thread closed");
               
           } catch(Exception e) {
                System.out.println("exception is" + e);
           }
     }
}

public classCloseChildThreadTest {
    public static void main(String args[]) throws InterruptedException {
    System.out.println("Main thread start");
    ChildThread1 cThread = new ChildThread1();
   
        cThread.setName("Child Thread");
        cThread.start();
       
        cThread.join();
        System.out.println("Main thread closed");
    }
}
Output:
Main thread start
Child thread start
Child thread closed
Main thread closed

Using CountDownLatch:
package com.thread;

importjava.util.concurrent.CountDownLatch;
classChildThread1 extends Thread {
     CountDownLatch latch;
     publicChildThread1(CountDownLatch latch) {
           this.latch = latch;
     }

     @Override
     public void run() {
           try {
                System.out.println("Child thread start");
                Thread th = Thread.currentThread();
               
                if("Child Thread".equals(th.getName())) {
                     Thread.sleep(1000);
                }
                System.out.println("Child thread closed");
                /* Count down when the run method execution finished. */
                latch.countDown();
           } catch(Exception e) {
                System.out.println("exception is" + e);
           }
     }
}

public classCloseChildThreadTest {
    public static void main(String args[]) throws InterruptedException {
        /*Set count 1 to CountDownLatch. */
        CountDownLatch latch = new CountDownLatch(1);
        System.out.println("Main thread start");
        ChildThread1 cThread = new ChildThread1(latch);

        cThread.setName("Child Thread");
        cThread.start();

        /* Await till the end of the Child thread. */
        latch.await();
        System.out.println("Main thread closed");
    }
}
Output:
Main thread start
Child thread start
Child thread closed
Main thread closed

Java Nested Interface

A nested interface is any regular interface whose declaration occurs within another class or interface. These interfaces are used to group related interfaces so that we can be easy to maintain.

Rules for Declaring Nested Interface
1. Nested interface must be public if it is declared inside the interface but it can have any access modifier if declared within the class.

2. Nested interfaces are implicitly static regardless of where they are declared (inside class or another interface).

interface OuterInter {
     void outerMethod();
     interface InnerInter {
           void method();
     } 

classNestedInterface implements OuterInter.InnerInter {
     public void method() {
           System.out.println("Hello nested interface");
     }

     public static void main(String args[]) {
           OuterInter.InnerInter message = new NestedInterface();//up-casting here
           message.method();
     }
}

Output: Hello nested interface

Application Use of Nested Interfaces

A static nested interface serves a great advantage to namespace resolution. This is the basic idea behind introducing nested interfaces and nested classes in Java.

For example, if you have an interface with an exceedingly common name, and in a large project, it is quite possible that some other programmer has the same idea, and has an interface with the same name you had, then you can solve this potential name clash by making your interface a public static nested interface.

Your interface will be known as outer class or outer interface, followed by a period (.), and then followed by static nested interface name.

Wednesday 24 August 2016

How to Stop Thread in Java?

By default, a Thread stops when execution of run() method finish either normally or due to any Exception.
It is tricky to stop the Thread execution in Java as stop() method has been deprecated from Thread Class.

To make the thread stop, we organise for the run() method to exit.

Stop using boolean State variable or flag:
It is very popular to stop a Thread using flag and it's also safe because it doesn't do anything special rather than helping run() method to finish itself.
class Runner extends Thread {
     private boolean exit = false;

     @Override
     public void run() {
           while(!exit) {
                System.out.println("Thread is running");
                try {
                     Thread.sleep(500);
                } catch(InterruptedException ex) {
                     System.out.println("Exception !!");
                }
           }
           System.out.println("Stopped !!");
     }
     public void exit(boolean bExit) {
           this.exit = bExit;
     }
}

public classThreadStopFlag {
     public static void main (String[] args) throwsInterruptedException {
           Runner runner = new Runner();
           runner.start();
           Thread.sleep(1000);
           runner.exit(true);
     }
}

Output:
Thread is running
Thread is running
Stopped !!

Stop using interrupt() method:
class Runner1 extends Thread {
     @Override
     public void run() {
           while (!Thread.currentThread().isInterrupted()) {
                System.out.println("Thread is running");
           }
           System.out.println("Stopped !!");
     }
}

public classThreadStopUsingInterrupt {
     public static void main (String[] args) throwsInterruptedException {
           Runner1 runner = new Runner1();
           runner.start();
          
           Thread.sleep(1);
          
           runner.interrupt();
     }
}
Output:
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Stopped !!

Related Posts Plugin for WordPress, Blogger...