Tuesday, 27 March 2018

Difference between final, finally and finalize()?

final :Final is a keyword.
Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final method can't be overridden and final variable value can't be changed.

finally:Finally is a block.
Finally is used to place important code, it will be executed whether exception is handled or not.

finalize: Finalize is a method.
Finalize is used to perform clean up processing just before object is garbage collected.

Why wait(), notify() and notifyAll() must be called from synchronized block or method in Java


We use wait(), notify(), or notifyAll() method mostly for inter-thread communication in Java.

One thread is waiting after checking a condition .Calling notify() or notifyAll() methods issues a notification to a single or multiple thread that a condition has changed and now all the threads which are waiting, fight for object lock on which they are waiting and lucky thread returns from wait() method after reacquiring the lock and proceed further.

which could lead to potential race condition and now how to  resolved it? This race condition is resolved by using synchronized keyword and locking provided by Java. In order to call the wait (), notify () or notifyAll () methods in Java, we must have obtained the lock for the object on which we're calling the method.

Since the wait() method in Java also releases the lock prior to waiting and reacquires the lock prior to returning from the wait() method, we must use this lock to ensure that checking the condition  and setting the condition is atomic which can be achieved by using synchronized method or block in Java.

Difference between yield and sleep in Java


The major difference between yield and sleep in Java is that yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent. Yield method doesn’t guarantee  that current thread will pause or stop but it guarantee that CPU will be relinquished by current Thread as a result of a call to Thread.yield() method in java.

1) Thread.sleep() method is used to pause the execution, relinquish the CPU and return it to thread scheduler.
2) Thread.sleep() method is a static method and always puts the current thread to sleep.
3) Java has two variants of sleep method in Thread class one with one argument which takes milliseconds as the duration of sleep and another method with two arguments one is millisecond and other is the nanosecond.
4) Unlike wait() method in Java, sleep() method of Thread class doesn't relinquish the lock it has acquired.
5) sleep() method throws Interrupted Exception if another thread interrupts a sleeping thread in java.
6) With sleep() in Java it's not guaranteed that when sleeping thread woke up it will definitely get CPU, instead it will go to Runnable state and fight for CPU with other thread.

List out difference between wait and sleep in Java .


A) wait is called from synchronized context only while sleep can be called without synchronized block.
B) wait for release lock on an object while waiting while sleep doesn’t release lock while waiting.
C)waiting thread can be awake by calling notify and notifyAll while sleeping thread can not be awakened by calling notify method.
D)The wait() method  is called on an Object on which the synchronized block is locked, while sleep is called on the Thread.
E)wait is normally done on condition, Thread wait until a condition is true while sleep is just to put your thread on sleep.
F) Thread.sleep() method is a static method and applies on current thread, while wait() is an instance specific method and only got wake up if some other thread calls notify method on same object.
G)also, in the case of sleep, sleeping thread immediately goes to Runnable state after waking up while in the case of wait, waiting for a thread first acquires the lock and then goes into Runnable state

Difference between Thread and Runnable interface in Java.


A. Java doesn't support multiple inheritance, which means you can only extend one class in Java so once you extended Thread class you lost your chance and can not extend or inherit another class in Java.

B.When you extends Thread class, each of your thread creates unique object and associate with it.
When you implements Runnable, it shares the same object to multiple threads.

C.Use Runnable interface when you want to access the same resource from the group of threads. Avoid using Thread class here, because multiple objects creation consumes more memory and it becomes a big performance overhead.

D.Loosely-coupled : "implements Runnable" makes the code loosely-coupled and easier to read .
Because the code is split into two classes . Thread class for the thread specific code and your Runnable implementation class for your job that should be run by a thread code.
"extends Thread"  makes the code tightly coupled . Single class contains the thread code as well as the job that needs to be done by the thread.

Difference between start and run in Java Thread


A. when program calls start() method a new Thread is created and code inside run() method is executed in new Thread while if you call run() method directly no new Thread is created and code inside run() will execute on current Thread.
B.Most of the time calling run() is bug or programming mistake because caller has intention of calling start() to create new thread .
C. If you want to perform time consuming task than always call start() method otherwise your main thread will stuck while performing time consuming task if you call run() method directly.
D.you can not call start() method twice on thread object. once started, second call of start() will throw IllegalStateException in Java while you can call run() method twice.

Difference between start and run method in Thread


Main difference is that when program calls start() method a new Thread is created and code inside run() method is executed in new Thread while if you call run() method directly no new Thread is created and code inside run() will execute on current Thread.
If you want to perform time consuming task than always call start() method otherwise your main thread will stuck while performing time consuming task if you call run() method directly.
Another difference between start vs run in Java thread is that you can not call start() method twice on thread object. once started, second call of start() will throw IllegalStateException in Java while you can call run() method twice.

Why finalize is declared protected instead of public?


making finalize protected looks good in terms of following rule of encapsulation which starts with least restrictive access modifier like private but making finalize private prevents it from being overridden in subclass as you can not override private methods, so making it protected is next obvious choice.
2) One of the most important points of finalize method is that it's not automatically chained like constructors. If you are overriding finalize method then it's your responsibility to call finalize() method of the superclass, if you forgot to call then finalize of super class will never be called.
3) finalize method is called by garbage collection thread before collecting object and if not intended to be called like a normal method.
4) finalize gets called only once by GC thread if object revives itself from finalize method than finalize will not be called again.
5) Any Exception is thrown by finalize method is ignored by GC thread and it will not be propagated further, in fact, I doubt if you find any trace of it.

Difference between final, finally and finalize()?

final :Final is a keyword.
Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final method can't be overridden and final variable value can't be changed.

finally:Finally is a block.
Finally is used to place important code, it will be executed whether exception is handled or not.

finalize: Finalize is a method.
Finalize is used to perform clean up processing just before object is garbage collected.

Why String is final or Immutable in Java ?


1) String Pool
String is going to be most used data type in all kind of Java applications.One of key step on that direction was idea of storing String literals in String pool. Goal was to reduce temporary String object by sharing them and in order to share, they must have to be from Immutable class. You can not share a mutable object with two parties which are unknown to each other.Example, where two reference variable is pointing to same String object:

String s1 = "Java";
String s2 = "Java";

Now if s1 changes the object from "Java" to "C++", reference variable also got value s2="C++", which it doesn't even know about it. By making String immutable, this sharing of String literal was possible. In short, key idea of String pool can not be implemented without making String final or Immutable in Java.


2) Security
String has been widely used as parameter for many Java classes, e.g. for opening network connection, you can pass host and port as String, for reading files in Java you can pass path of files and directory as String and for opening database connection, you can pass database URL as String.
If String was not immutable, a user might have granted to access a particular file in system, but after authentication he can change the PATH to something else, this could cause serious security issues. Similarly, while connecting to database or any other machine in network, mutating String value can pose security threats.

3) Use of String in Class Loading Mechanism
Another reason for making String final or Immutable was driven by the fact that it was heavily used in class loading mechanism. As String been not Immutable, an attacker can take advantage of this fact and a request to load standard Java classes e.g. java.io.Reader can be changed to malicious class com.unknown.DataStolenReader. By keeping String final and immutable, we can at least be sure that JVM is loading correct classes.


4) Multithreading Benefits
Since Concurrency and Multi-threading was Java's key offering, it made lot of sense to think about thread-safety of String objects. Since it was expected that String will be used widely, making it Immutable means no external synchronization, means much cleaner code involving sharing of String between multiple threads. This single feature, makes already complicate, confusing and error prone concurrency coding much easier. Because String is immutable and we just share it between threads, it result in more readable code.


5) Optimization and Performance
Now when you make a class Immutable, you know in advance that, this class is not going to change once created. This guarantee open path for many performance optimization e.g. caching. String itself know that, I am not going to change, so String cache its hashcode. It even calculate hashcode lazily and once created, just cache it. In simple world, when you first call hashCode() method of any String object, it calculate hash code and all subsequent call to hashCode() returns already calculated, cached value. This results in good performance gain, given String is heavily used in hash based Maps e.g. Hashtable and HashMap. Caching of hashcode was not possible without making it immutable and final, as it depends upon content of String itself.

How to create Immutable class in Java?


Following are the requirements:
        Class must be declared as final (So that child classes can’t be created)
        Data members in the class must be declared as final (So that we can’t change the value of it after object creation)
        A parameterized constructor
        Getter method for all the variables in it
        No setters(To not have option to change the value of the instance variable)


public final class Student
{
    final String name;
    final int regNo;

    public Student(String name,int regNo)
    {
        this.name=name;
        this.regNo=regNo;
    }
    public String getName()
    {
        return name;
    }
    public int getRegNo()
    {
        return regNo;
    }
}

Simple Thread example to use synchronization.


package com.test.yuvagen.basic;

/* Simple Thread example to use synchronization  
 * Read more:http://javainterviewprograms.blogspot.in/
 * */

public class SendMessageThread {

          public void sendMessage(String msg) {
                   System.out.println("sending\t" + msg);
                   try {
                             Thread.sleep(1000);
                   } catch (Exception e) {
                             e.printStackTrace();
                   }

          }

          public static void main(String args[]) {

                   SendMessageThread smT = new SendMessageThread();
                   ThreadSend th = new ThreadSend("Hi", smT);
                   ThreadSend th2 = new ThreadSend("Bye", smT);

                   th.start();
                   th2.start();

                   try {
                             th.join();
                             th2.join();
                   } catch (Exception e) {
                             e.printStackTrace();
                   }

          }
}

class ThreadSend extends Thread {
          private String str;
          private Thread th;
          SendMessageThread sm;

          ThreadSend(String msg, SendMessageThread smObj) {
                   str = msg;
                   sm = smObj;
          }

          @Override
          public void run() {
                   synchronized (sm) {
                             sm.sendMessage(str);
                   }
          }

}
Output:
sending     Hi
sending     Bye

Return statement in try catch block.


package com.test.yuvagen.basic;

/* Return in try catch block
 * We can have return statement in try catch block but finally block               *will be executed
 * Read more:http://javainterviewprograms.blogspot.in/
 * */

public class ReturnInTryCatch {

          public int returnSomething(int number) {
                   int num = 0;
                   try {
                             num = number / 0;
                             return num;
                   } catch (Exception e) {
                             e.printStackTrace();
                             return num;
                   } finally {
                             System.out.println("I am in finally");
                   }

          }

          public static void main(String args[]) {
                   ReturnInTryCatch ritc = new ReturnInTryCatch();
                   System.out.println(ritc.returnSomething(10));
          }
}

Output:
java.lang.ArithmeticException: / by zero
I am in finally
0
at com.test.yuvagen.basic.ReturnInTryCatch.returnSomething(ReturnInTryCatch.java:8)                                                                                                                 at com.test.yuvagen.basic.ReturnInTryCatch.main(ReturnInTryCatch.java:23)

Please demonstrate Lock Interface using Example?


package com.test.yuvagen.basic;

import java.util.concurrent.locks.*;
/* Write a Java program that Demonstrate Lock Interface  
 * */
public class LockThreadDemo {

          private final Lock queueLock = new ReentrantLock();

          public void print() {

                   queueLock.lock();

                   try {
                             Long duration = (long) (Math.random() * 10000);
                             System.out.println(Thread.currentThread().getName() + "\ttime taken" + (duration / 1000) + "sec");
                             Thread.sleep(duration);
                   } catch (Exception e) {
                             e.printStackTrace();
                   } finally {
                             queueLock.unlock();
                   }
          }

          public static void main(String args[]) {
                   LockThreadDemo lockDemo = new LockThreadDemo();

                   ThreadLock tl1 = new ThreadLock("Thread-1", lockDemo);
                   ThreadLock tl2 = new ThreadLock("Thread-2", lockDemo);
                   ThreadLock tl3 = new ThreadLock("Thread-3", lockDemo);

                   tl1.start();
                   tl2.start();
                   tl3.start();
          }
}

class ThreadLock extends Thread {
          LockThreadDemo lockDemo;

          ThreadLock(String name, LockThreadDemo lockDemo) {
                   super(name);
                   this.lockDemo = lockDemo;
          }

          @Override
          public void run() {
                   lockDemo.print();
          }
}

Output:
Thread-1   time taken3sec
Thread-2   time taken5sec
Thread-3   time taken6sec


Difference between final, finally and finalize()?

final :Final is a keyword. Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final ...