1).What is Multithreading in java
ANS: Multithreading in java is a process of executing multiple threads simultaneously.
Thread is basically a lightweight sub-process, a smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
2).What is thread?Why we are using threads?
ANS:
thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution.
Threads are independent, if there occurs exception in one thread, it doesn't affect other threads.
It shares a common memory area.
3).What is the difference b/w Process and Thread in java?
ANS:
PROCESS:
Each process have its own address in memory i.e. each process allocates separate memory area.
Process is heavyweight.
Cost of communication between the process is high.
thread:
thread is a lightweight sub process, a smallest unit of processing.
It is a separate path of execution.
Threads are independent, if there occurs exception in one thread,
it doesn't affect other threads.
It shares a common memory area.
4).How many ways to implement the thread in java?Which approach is best?Exaplin
ans:
There are two ways to create a thread:
* By extending Thread class
* By implementing Runnable interface.
By extending Thread class
Thread class provide constructors and methods to create and perform operations on a thread.
Thread class extends Object class and implements Runnable interface.
By implementing Runnable interface.
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.
Runnable interface have only one method named run().
ans:
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
5).When to use Runnable and Thread?
ans:
You usually extend a class to add or modify functionality. ...
In the same light, if you don't need to inherit thread methods, you can do without that overhead by using Runnable.
Single inheritance: If you extend Thread you cannot extend from any other class, so if that is what you need to do, you have to use Runnable.
6).Explain thread methods?
public void run(): is used to perform action for a thread.
public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.
public void join(): waits for a thread to die.
public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the thread.
public String getName(): returns the name of the thread.
public void setName(String name): changes the name of the thread.
public Thread currentThread(): returns the reference of currently executing thread.
public int getId(): returns the id of the thread.
public Thread.State getState(): returns the state of the thread.
public boolean isAlive(): tests if the thread is alive.
public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute.
public void suspend(): is used to suspend the thread(depricated).
public void resume(): is used to resume the suspended thread(depricated).
public void stop(): is used to stop the thread(depricated).
public boolean isDaemon(): tests if the thread is a daemon thread.
public void setDaemon(boolean b): marks the thread as daemon or user thread.
public void interrupt(): interrupts the thread.
public boolean isInterrupted(): tests if the thread has been interrupted.
public static boolean interrupted(): tests if the current thread has been interrupted.
ans:
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
8).How to create the thread safe of objects and thread safe methods?
9).Runnable vs Callable?
ans:
A Runnable object does not return a result whereas a Callable object returns a result.
A Runnable object cannot throw a checked exception wheras a Callable object can throw an exception.
The Runnable interface has been around since Java 1.0 whereas Callable was only introduced in Java 1.5.
Few similarities include
Instances of the classes that implement Runnable or Callable interfaces are potentially executed by another thread.
Instance of both Callable and Runnable interfaces can be executed by ExecutorService via submit() method.
10).What is the difference b/w Synchronized methods and Synchronized blocks?
ans:
Synchronized methode:
If you declare any method as synchronized, it is known as synchronized method.
Synchronized method is used to lock an object for any shared resource.
Synchronized block:
Synchronized block can be used to perform synchronization on any specific resource of the method.
Synchronized block is used to lock an object for any shared resource.
Scope of synchronized block is smaller than the method.
11).What is the use of "volatile",native and "synchronized" keywords?
ans:
volatile:
volatile is a modifier applicable only variables,if a variable is declare as volatile then every thread a seperate local copy will be created
synchronized:
synchronized keword is apply to only blocks and method,
if a method or block declare as a synchronized then at time only one thread is allowd to operate on the given object
the main advantage is to reduce the data inconsistency problem
the main disadvantage is increase the waiting time of thread effects the perfoamnce of the system
12).What is Serialization?Expalin with example.
ans:Serialization in java is a mechanism of writing the state of an object into a byte stream.
It is mainly used in Hibernate, RMI, JPA, EJB, JMS technologies.
The reverse operation of serialization is called deserialization.
ex:
class Persist{
public static void main(String args[])throws Exception{
Student s1 =new Student(211,"ravi");
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
System.out.println("success");
}
}
13).When we are using the serialization?
ans:
It is mainly used to travel object's state on the network (known as marshaling).
14).What is deserialization?Explain with example.
ans:
The reverse operation of serialization is called deserialization.
ex;
import java.io.*;
class Depersist{
public static void main(String args[])throws Exception{
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject();
System.out.println(s.id+" "+s.name);
in.close();
}
}
15).What is thread safety?Explain.
Adding synchronized to this method will makes it thread-safe.
When synchronized is added to a static method, the Class object is the object which is locked
Synchronization is the easiest and most widely used tool for thread safety in java.
Use of locks from java.util.concurrent.locks package.
Using thread safe collection classes, check this post for usage of ConcurrentHashMap for thread safety.
Using volatile keyword with variables to make every thread read the data from memory, not read from thread cach
16).What is the difference b/w wait() and notify and notifyAll()?
ans:
1.wait()
the wait() method is defined in object class
wait() method release the lock
2.notify()'
notify() is used to unblock one thread
3.notifyAll()
notifyAll() is used to unblock all the threads in waiting state
17).What is the difference b/w sleep() and wait() methods?
1.sleep()
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
sleep() method define in thread class
sleep) method does not release the lock
2.wait()
the wait() method is defined in object class
wait() method release the lock
18).What is the difference b/w sleep() and join() methods?
1.sleep()
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
2.join()
The join() method waits for a thread to die. In other words,
it causes the currently running threads to stop executing until the thread it joins with completes its task.
19).What is the difference b/w join() and yield() methods?
1.join()
The join() method waits for a thread to die. In other words,
it causes the currently running threads to stop executing until the thread it joins with completes its task.
2.yield()
yield() method is used to puase the current excuting thread for giving the chance to remaining waiting threads
20).How do you share the data b/w threads?(Interthread communication).
ans:
If two threads will communicate with each other by using wait() & notify(),notifyAll() is called inter Therad Communication
21).What is the use of start() and run() methods?Explain.
ans:
start() methode:
starts the execution of the thread.JVM calls the run() method on the thread.
run methode:
is used to perform action for a thread.
22).What is deadlock()?Explain.
ans:
if two threads are waiting for each other for ever such type of sittuation is called deadlock()
23).Explain locking concept in threads, and What is the difference b/w Object level lock and class level lock?
24).What is daemon thread?Give one example for daemon thread and How to create daemon thread?
ans:
Daemon thread in java is a service provider thread that provides services to the user thread.
Its life depend on the mercy of user threads i.e. when all the user threads dies,
JVM terminates this thread automatically.
There are many java daemon threads running automatically e.g. gc, finalizer etc.
25).How to stop the thread in java?
ans:
we can stop a thread excution in the middle by using stop() method.
then the thread will be enter into dead state
26).What is thread priority?
ans:
Each thread have a priority. Priorities are represented by a number between 1 and 10.
In most cases, thread schedular schedules the threads according to their priority (known as preemptive scheduling).
But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.
27).What is the use of transient keyword?
ans:
transient:
transient is a keyword applicable only variables,at the time of serialization if we don't want save the value of a particular variable
to meet security constraints then we should go for transient.
at the time of serialization jvm ignore the original value of the transient variable and default value will be serializable
28).Difference b/w Serialization and Externalization?
ans:
Serialization in java is a mechanism of writing the state of an object into a byte stream.
It is mainly used in Hibernate, RMI, JPA, EJB, JMS technologies.
The reverse operation of serialization is called deserialization.