Difference between JDK, JRE and JVM
JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed. |
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform dependent because configuration of each OS differs. But, Java is platform independent. |
The JVM performs following main tasks:
|
JRE
JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is the implementation of JVM.It physically exists.It contains set of libraries + other files that JVM uses at runtime. |
If you want to run any java program, you need to have JRE installed in the system. JRE is targeted for execution of Java files i.e. JRE = JVM + Java Packages Classes(like util, math, lang, awt,swing etc)+runtime libraries. |
JDK
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development tools. JDK is mainly targeted for java development. i.e. You can create a Java file (with the help of Java packages), compile a Java file and run a java file. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Diagram to show the relations between JVM, JRE and JDK
Difference between Array and ArrayList in Java
Difference between ArrayList and LinkedList in Java
Difference between HashMap and Hashtable in Java
How ConcurrentHashMap gives better performance as compared to Synchronized HashMap?
Ans: ConcurrentHashMap maintains a list of 16 locks by default ( number of locks equal to the initial capacity , which is by default 16) each of which is used to lock on a single bucket of the Map.This indicates that 16 threads (number of threads equal to the concurrency level , which is by default 16) can modify the collection at the same time , given ,each thread works on different bucket. So unlike hashtable, we perform any sort of operation ( update ,delete ,read ,create) without locking on entire map in ConcurrentHashMap.
What is difference between StringBuffer and StringBuilder in Java ?
StringBuilder in Java is introduced in Java 5 and only difference between both of them is that Stringbuffer methods are synchronized while StringBuilder is non synchronized.
What will happen if you call return statement or System.exit on try or catch block ? will finally block execute?
Ans: finally block will execute even if you put return statement in try block or catch block but finally block won’t run if you call System.exit form try or catch.
Can you override private or static method in Java ?
Ans: you can not override private or static method in Java, if you create similar method with same return type and same method arguments that’s called method hiding.
What will happen if we put a key object in a HashMap which is already there ?
Ans: if you put the same key again than it will replace the old mapping because HashMap doesn’t allow duplicate keys.
What is the difference between final, finally, and finalize?
When applied to a method: The method cannot be overridden. When applied to a class: The class cannot be sub-classed. There is an optional finally block after the try block or after the catch block. Statements in the finally block will always be executed (except if JVM exits from the try block). The finally block is used to write the clean up code. This is the method that the JVM runs before running the garbage collector. |
Object
requires that if two objects are equal according to equals() method
, then they must have the same hashCode()
value.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| <div> <pre> public class RunnableExample implements Runnable { public void run() {</pre> <pre> System.out.println( "Alive is awesome" );</pre> <pre> }</pre> <pre>} </pre> </div> <div> <pre> public class ThreadExample extends Thread { public void run() {</pre> <pre> System.out.println( " Love Yourself " );</pre> <pre> }</pre> <pre>} |
Recap : Difference between “implements Runnable” and “extends Thread”
implements Runnable | extends Thread | |
---|---|---|
Inheritance option | extends any java class | No |
Reusability | Yes | No |
Object Oriented Design | Good,allows composition | Bad |
Loosely Coupled | Yes | No |
Function Overhead | No | Yes |
What is BlockingQueue in Java Collections Framework?
BlockingQueue implements the java.util.Queue interface . BlockingQueue supports operations that wait for the queue to become non-empty when retrieving an element , and wait for space to become available in the queue when storing an element .
It does not accept null elements.
Blocking queues are primarily designed for the producer-consumer problems.
BlockingQueue implementations are thread-safe and can also be used in inter-thread communications. This concurrent Collection class was added in jdk 1.5
It does not accept null elements.
Blocking queues are primarily designed for the producer-consumer problems.
BlockingQueue implementations are thread-safe and can also be used in inter-thread communications. This concurrent Collection class was added in jdk 1.5
Difference between wait and sleep methods
1. Class belongs : The wait() method belongs to java.lang.Object class, thus can be called on any Object. The sleep() method belongs to java.lang.Thread class, thus can be called on Threads.
2. Context : The wait() method can only be called from Synchronized context i.e. using synchronized block or synchronized method. The sleep() method can be called from any context.
3. Locking : The wait() method releases the lock on an object and gives others chance to execute. The sleep() method does not releases the lock of an object for specified time or until interrupt.
4. Wake up condition : A waiting thread can be awake by notify() or notifyAll() method. A sleeping can be awaked by interrupt or time expires.
5. Execution : Each object has each wait() method for inter-communication between threads. The sleep() method is static method belonging to Thread class. There is a common mistake to write t.sleep(1000) because sleep() is a class method and will pause the current running thread not t.
Recap : Difference between Sleep and Wait in Java
Sleep | Wait | |
---|---|---|
Class belongs | java.lang.Thread | java.lang.Object |
Context | Called from any context | Only synchronized context |
Locking | Does not release the lock for specified time or until interrupt. | Releases the lock |
Wake up Condition | When time expires or due to interruption | Awake by call to notify() or notifyAll() method |
Execution | Execution of sleep will pause the current running thread not the object on which it is called. | Thread wait() continues till a specific condition holds true |
How can we create a Thread in Java?
Ans: There are two ways to create Thread in Java – first by implementing Runnable interface and then creating a Thread object from it and second is to extend the Thread Class.
Can a thread call a non-synchronized instance method of an Object when a synchronized method is being executed ?
Ans: Yes, a Non synchronized method can always be called without any problem. In fact Java does not do any check for a non-synchronized method. The Lock object check is performed only for synchronized methods/blocks.
Can two threads call two different synchronized instance methods of an Object?
Ans: No. If a object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed.
Can we synchronize the run method? If yes then what will be the behavior?
Ans: Yes, the run method of a runnable class can be synchronized. If you make run method synchronized then the lock on runnable object will be occupied before executing the run method. In case we start multiple threads using the same runnable object in the constructor of the Thread then it would work. But until the 1st thread ends the 2nd thread cannot start and until the 2nd thread ends the next cannot start as all the threads depend on lock on same object.
Can we call run() method of a Thread class?
Ans: Yes, we can call run() method of a Thread class but then it will behave like a normal method. To actually execute it in a Thread, we need to start it using Thread.start() method.
What is thread pool? Why should we use thread pools?
Ans: A thread pool is a collection of threads on which task can be scheduled. Instead of creating a new thread for each task, you can have one of the threads from the thread pool pulled out of the pool and assigned to the task. When the thread is finished with the task, it adds itself back to the pool and waits for another assignment.
Can we synchronize the constructor of a Java Class?
Ans: As per Java Language Specification, constructors cannot be synchronized because other threads cannot see the object being created before the thread creating it has finished it.
What is a volatile keyword?
Ans: The copy of volatile variable is stored in the main memory, so every time a thread access the variable even for reading purpose the local copy is updated each time from the main memory. The volatile variable also have performance issues.
What is the difference between wait() and sleep()?
Ans:
1) The wait() method is defined in Object class. The sleep() method is defined in Thread class.
2) The wait() method releases the lock. The sleep() method does not release the lock.
3) The wait() method should be called from synchronized method or block. There is no such requirement for sleep() method.
4) The wait() method is an instance specific method and only got wake up if some other thread calls notify or notifyAll methods on same object.The sleep() method is a static method and applies on current thread.
Ans:
1) The wait() method is defined in Object class. The sleep() method is defined in Thread class.
2) The wait() method releases the lock. The sleep() method does not release the lock.
3) The wait() method should be called from synchronized method or block. There is no such requirement for sleep() method.
4) The wait() method is an instance specific method and only got wake up if some other thread calls notify or notifyAll methods on same object.The sleep() method is a static method and applies on current thread.
What is the difference between yield() and sleep()?
Ans: yield() allows the current the thread to release its lock from the object and scheduler gives the lock of the object to the other thread with same priority.
sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t release the lock.
sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t release the lock.
How many locks does an object have?
Ans: Each object has only one lock.
What does join() method do?
Ans: t.join( ) allows the current thread to wait indefinitely until thread “t” is finished. t.join (5000) allows the current thread to wait for thread “t” to finish but does not wait longer than 5 seconds. Note that join() can also take times in milliseconds and nanoseconds as parameters. These values specify the maximum amount of time to wait before returning the blocked thread’s state to RUNNABLE.
The following statements are true.
1. wait( ), notify( ), notifyall( ) are defined as final & can be called only from within a synchronized method
2. Among wait( ), notify( ), notifyall( ) the wait() method only throws IOException
1. wait( ), notify( ), notifyall( ) are defined as final & can be called only from within a synchronized method
2. Among wait( ), notify( ), notifyall( ) the wait() method only throws IOException
You have thread T1, T2 and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2?
Ans: It can be achieved by using join method of Thread class.
Why we call start() method which in turns calls run() method, why not we directly call run() method ?
Ans: when you call start() method it creates new Thread and execute code declared in run() while directly calling run() method doesn’t create any new thread and execute code on same calling thread.
What is Java Thread Dump, How can we get Java Thread dump of a Program?
Ans: Thread dump is list of all the threads active in the JVM, thread dumps are very helpful in analyzing bottlenecks in the application and analyzing deadlock situations. There are many ways using which we can generate Thread dump – Using Profiler, Kill -3 command, jstack tool etc.
What is ReentrantLock? How it is different from synchronized?
Ans: The ReentrantLock has the same concurrency and memory semantics as synchronized. It also provides features like lock polling, timed lock waits, and interruptible lock waits. Additionally, it offers far better performance under heavy contention.
Protecting a block of code with ReentrantLock:
1
2
3
4
5
6
7
8
9
| Lock lock = new ReentrantLock(); lock.lock(); try { // update object state } finally { lock.unlock(); } |
We can use the ReentrantLock when we actually need something it provides that synchronized doesn’t, like timed lock waits, interruptible lock waits etc. It also has scalability benefits, and you should use it if you actually have a situation that exhibits high contention. However, the existences of these obvious benefits are not a good enough reason to always prefer ReentrantLock over synchronized.
In majority of the cases, synchronized works just fine, works on all JVMs, is understood by a wider range of developers, and is less error-prone. So make the decision on the basis of need.
How to Stop a Thread in java?
Ans: We can use Thread.interrupt() to stop a Thread.
Difference between run() and start() methods of Thread?
Ans: The start() method creates a new thread and then execute the run() method.
The run() method just executes in the current thread, without starting a new thread.
The run() method just executes in the current thread, without starting a new thread.
When will a ConcurrentModificationException happen?
A ConcurrentModificationException will happen if an iterator of a collection is being traversed while at the time the collection is being modified. For example, if you are looping through an iterator of a set and at the time you try to remove or add element to the set.
What is AtomicInteger class and how is it different than using volatile or synchronized?
Ans: An int value that may be updated atomically. An AtomicInteger is used in applications where we need to atomically increment counters.
If the variable declared as Volatile then it always takes master copy of variable instead of local copy of a variable.
If the method or block of code marked as syschronized then it prevents multiple threads accessing that part of the code
What are all the possible ways to make a class is not extendable in java?
Ans:
1. Let’s create a class as final class.
2. Let’s make all the constructors in a class as private.
Difference between HashTable and HashMap
1. HashTable is synchronized, whereas HashMap it not synchronized.
2. HashTable does not allow null keys or values. HashMap allows one null key and any number of null vlaues.
2. HashTable does not allow null keys or values. HashMap allows one null key and any number of null vlaues.
Difference between ConcurrentHashMap and HashTable
The major advantage of using ConcurrentHashMap is “performance” as the lock is not applied on whole Map as is the case with Hashtable.
ConcurrentHashMap is offering all the features of Hashtable with a performance almost as good as a HashMap. ConcurrentHashMap’s accomplish this by a very simple mechanism. Instead of a map wide lock, the collection maintains a list of 16 locks by default, each of which is used to guard (or lock on) a single bucket of the map. This effectively means that 16 threads can modify the collection at a single time (as long as they’re all working on different buckets). Infact there is no operation performed by this collection that locks the entire map. The concurrency level of the collection, the number of threads that can modify it at the same time without blocking, can be increased. However a higher number means more overhead of maintaining this list of locks.
How will you awake a blocked thread in java?
Ans: We can awake the thread by throwing InterruptedException if it is blocked by calling wait(), sleep() or join() methods. I don’t think there is a way to awake the thread if it is blocked on IO.Different ways to create objects in Java
Here are four different ways to create objects in java:
1. Using new keyword
This is the most common way to create an object in java. I read somewhere that almost 99% of objects are created in this way.
MyObject object = new MyObject();
This is the most common way to create an object in java. I read somewhere that almost 99% of objects are created in this way.
MyObject object = new MyObject();
2. Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.
MyObject object = (MyObject) Class.forName(“subin.rnd.MyObject”).newInstance();
If we know the name of the class & if it has a public default constructor we can create an object in this way.
MyObject object = (MyObject) Class.forName(“subin.rnd.MyObject”).newInstance();
3. Using clone()
The clone() can be used to create a copy of an existing object.
MyObject anotherObject = new MyObject();
MyObject object = anotherObject.clone();
The clone() can be used to create a copy of an existing object.
MyObject anotherObject = new MyObject();
MyObject object = anotherObject.clone();
4. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();
Now you know how to create an object. But its advised to create objects only when it is necessary to do so.
No comments:
Post a Comment