Java Interview Questions Part 7

What are the functions of the JDBC Connection interface?

The Connection interface maintains a session with the database. It can be used for transaction management. It provides factory methods that return the instance of Statement, PreparedStatement, CallableStatement, and DatabaseMetaData.

What does JDBC setMaxRows  method do?

The setMaxRows(int i) method limits the number of rows the database can return by using the query. This can also be done within the query as we can use the limit cause in MySQL.

What is multithreading?

Multithreading is a process of executing multiple threads simultaneously. Multithreading is used to obtain the multitasking. It consumes less memory and gives the fast and efficient performance. Its main advantages are:

  • Threads share the same address space.
  • The thread is lightweight.
  • The cost of communication between the processes is low.

More details.

 

What is the thread?

A thread is a lightweight subprocess. It is a separate path of execution because each thread runs in a different stack frame. A process may contain multiple threads. Threads share the process resources, but still, they execute independently.

More details.

 

 

Differentiate between process and thread?

There are the following differences between the process and thread.

  • A Program in the execution is called the process whereas; A thread is a subset of the process
  • Processes are independent whereas threads are the subset of process.
  • Process have different address space in memory, while threads contain a shared address space.
  • Context switching is faster between the threads as compared to processes.
  • Inter-process communication is slower and expensive than inter-thread communication.
  • Any change in Parent process doesn't affect the child process whereas changes in parent thread can affect the child thread.

What are the states in the lifecycle of a Thread?

A thread can have one of the following states during its lifetime:

  1. New: In this state, a Thread class object is created using a new operator, but the thread is not alive. Thread doesn't start until we call the start() method.
  2. Runnable: In this state, the thread is ready to run after calling the start() method. However, the thread is not yet selected by the thread scheduler.
  3. Running: In this state, the thread scheduler picks the thread from the ready state, and the thread is running.
  4. Waiting/Blocked: In this state, a thread is not running but still alive, or it is waiting for the other thread to finish.
  5. Dead/Terminated: A thread is in terminated or dead state when the run() method exits.

 

Differentiate between the Thread class and Runnable interface for creating a Thread?

The Thread can be created by using two ways.

  • By extending the Thread class
  • By implementing the Thread class

However, the primary differences between both the ways are given below:

  • By extending the Thread class, we cannot extend any other class, as Java does not allow multiple inheritances while implementing the Runnable interface; we can also extend other base class(if required).
  • By extending the Thread class, each of thread creates the unique object and associates with it while implementing the Runnable interface; multiple threads share the same object
  • Thread class provides various inbuilt methods such as getPriority(), isAlive and many more while the Runnable interface provides a single method, i.e., run().

 

Describe the purpose and working of sleep() method.

The sleep() method in java is used to block a thread for a particular time, which means it pause the execution of a thread for a specific time. There are two methods of doing so.

Syntax:

  • public static void sleep(long milliseconds)throws InterruptedException
  • public static void sleep(long milliseconds, int nanos)throws InterruptedException

Working of sleep() method

When we call the sleep() method, it pauses the execution of the current thread for the given time and gives priority to another thread(if available). Moreover, when the waiting time completed then again previous thread changes its state from waiting to runnable and comes in running state, and the whole process works so on till the execution doesn't complete.


14) What is the difference between wait() and sleep() method?

wait()

sleep()

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 doesn't release

the lock.

 

 

Can we call the run() method instead of start()?

Yes, calling run() method directly is valid, but it will not work as a thread instead it will work as a normal object. There will not be context-switching between the threads. When we call the start() method, it internally calls the run() method, which creates a new stack for a thread while directly calling the run() will not create a new stack.

More details.

 

What about the daemon threads?

The daemon threads are the low priority threads that provide the background support and services to the user threads. Daemon thread gets automatically terminated by the JVM if the program remains with the daemon thread only, and all other user threads are ended/died. There are two methods for daemon thread available in the Thread class:

  • public void setDaemon(boolean status): It used to mark the thread daemon thread or a user thread.
  • public boolean isDaemon(): It checks the thread is daemon or not.

More details.

 

Can we make the user thread as daemon thread if the thread is started?

No, if you do so, it will throw IllegalThreadStateException. Therefore, we can only create a daemon thread before starting the thread.

  1. class Testdaemon1 extends Thread{    
  2. public void run(){  
  3.           System.out.println("Running thread is daemon...");  
  4. }  
  5. public static void main (String[] args) {  
  6.       Testdaemon1 td= new Testdaemon1();  
  7.       td.start();  
  8.       setDaemon(true);// It will throw the exception: td.   
  9.    }  

10. }  

Output

Running thread is daemon...

Exception in thread "main" java.lang.IllegalThreadStateException

at java.lang.Thread.setDaemon(Thread.java:1359)

at Testdaemon1.main(Testdaemon1.java:8)

More details.


 

What is the synchronization?

Synchronization is the capability to control the access of multiple threads to any shared resource. It is used:


  1. To prevent thread interference.
  2. To prevent consistency problem.

When the multiple threads try to do the same task, there is a possibility of an erroneous result, hence to remove this issue, Java uses the process of synchronization which allows only one thread to be executed at a time. Synchronization can be achieved in three ways:

  • by the synchronized method
  • by synchronized block
  • by static synchronization

Syntax for synchronized block

  1. synchronized(object reference expression)  
  2.     {  
  3.         //code block  
  4.     }  
  5.       

More details.

 

 

What is context switching?

In Context switching the state of the process (or thread) is stored so that it can be restored and execution can be resumed from the same point later. Context switching enables the multiple processes to share the same CPU.

 

Is it possible to start a thread twice?

No, we cannot restart the thread, as once a thread started and executed, it goes to the Dead state. Therefore, if we try to start a thread twice, it will give a runtimeException "java.lang.IllegalThreadStateException". Consider the following example.

  1. public class Multithread1 extends Thread  
  2. {  
  3.    public void run()  
  4.     {  
  5.       try {  
  6.           System.out.println("thread is executing now........");  
  7.       } catch(Exception e) {  
  8.       }   
  9.     }  
  10. 10.     public static void main (String[] args) {  
  11. 11.         Multithread1 m1= new Multithread1();  
  12. 12.         m1.start();  
  13. 13.         m1.start();  
  14. 14.     }  

15. }  

Output

thread is executing now........

Exception in thread "main" java.lang.IllegalThreadStateException

        at java.lang.Thread.start(Thread.java:708)

        at Multithread1.main(Multithread1.java:13)

More details.

 

 

What is Thread Scheduler in java?

In Java, when we create the threads, they are supervised with the help of a Thread Scheduler, which is the part of JVM. Thread scheduler is only responsible for deciding which thread should be executed. Thread scheduler uses two mechanisms for scheduling the threads: Preemptive and Time Slicing.

Java thread scheduler also works for deciding the following for a thread:

  • It selects the priority of the thread.
  • It determines the waiting time for a thread
  • It checks the Nature of thread

 

What is the difference between preemptive scheduling and time slicing?

Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

What is the purpose of wait() method in Java?

The wait() method is provided by the Object class in Java. This method is used for inter-thread communication in Java. The java.lang.Object.wait() is used to pause the current thread, and wait until another thread does not call the notify() or notifyAll() method. Its syntax is given below.

public final void wait()

What do you understand by inter-thread communication?

  • The process of communication between synchronized threads is termed as inter-thread communication.
  • Inter-thread communication is used to avoid thread polling in Java.
  • The thread is paused running in its critical section, and another thread is allowed to enter (or lock) in the same critical section to be executed.
  • It can be obtained by wait(), notify(), and notifyAll() methods.

What are the advantages of multithreading?

Multithreading programming has the following advantages:

  • Multithreading allows an application/program to be always reactive for input, even already running with some background tasks
  • Multithreading allows the faster execution of tasks, as threads execute independently.
  • Multithreading provides better utilization of cache memory as threads share the common memory resources.
  • Multithreading reduces the number of the required server as one server can execute multiple threads at a time.

What is shutdown hook?

The shutdown hook is a thread that is invoked implicitly before JVM shuts down. So we can use it to perform clean up the resource or save the state when JVM shuts down normally or abruptly. We can add shutdown hook by using the following method:

  1. public void addShutdownHook(Thread hook){}    
  2. Runtime r=Runtime.getRuntime();  
  3. r.addShutdownHook(new MyThread());  

Some important points about shutdown hooks are :

  • Shutdown hooks initialized but can only be started when JVM shutdown occurred.
  • Shutdown hooks are more reliable than the finalizer() because there are very fewer chances that shutdown hooks not run.
  • The shutdown hook can be stopped by calling the halt(int) method of Runtime class.

More details.

 

What is the difference between notify() and notifyAll()?

The notify() is used to unblock one waiting thread whereas notifyAll() method is used to unblock all the threads in waiting state.

What does join() method?

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. Join method is overloaded in Thread class in the following ways.

  • public void join()throws InterruptedException
  • public void join(long milliseconds)throws InterruptedException

More details.

 

What is the deadlock?

Deadlock is a situation in which every thread is waiting for a resource which is held by some other waiting thread. In this situation, Neither of the thread executes nor it gets the chance to be executed. Instead, there exists a universal waiting state among all the threads. Deadlock is a very complicated situation which can break our code at runtime.

More details.

 

What is race-condition?

A Race condition is a problem which occurs in the multithreaded programming when various threads execute simultaneously accessing a shared resource at the same time. The proper use of synchronization can avoid the Race condition.

When should we interrupt a thread?

We should interrupt a thread when we want to break out the sleep or wait state of a thread. We can interrupt a thread by calling the interrupt() throwing the InterruptedException.

More details.

 

What do you understand by thread pool?

  • Java Thread pool represents a group of worker threads, which are waiting for the task to be allocated.
  • Threads in the thread pool are supervised by the service provider which pulls one thread from the pool and assign a job to it.
  • After completion of the given task, thread again came to the thread pool.
  • The size of the thread pool depends on the total number of threads kept at reserve for execution.

The advantages of the thread pool are :

  • Using a thread pool, performance can be enhanced.
  • Using a thread pool, better system stability can occur.

What is the purpose of the Synchronized block?

The Synchronized block can be used to perform synchronization on any specific resource of the method. Only one thread at a time can execute on a particular resource, and all other threads which attempt to enter the synchronized block are blocked.

  • Synchronized block is used to lock an object for any shared resource.
  • The scope of the synchronized block is limited to the block on which, it is applied. Its scope is smaller than a method.

More details.

 

How is the safety of a thread achieved?

If a method or class object can be used by multiple threads at a time without any race condition, then the class is thread-safe. Thread safety is used to make a program safe to use in multithreaded programming. It can be achieved by the following ways:

  • Synchronization
  • Using Volatile keyword
  • Using a lock based mechanism
  • Use of atomic wrapper classes

 

Does each thread have its stack in multithreaded programming?

Yes, in multithreaded programming every thread maintains its own or separate stack area in memory due to which every thread is independent of each other.

 

What is static synchronization?

If you make any static method as synchronized, the lock will be on the class not on the object. If we use the synchronized keyword before a method so it will lock the object (one thread can access an object at a time) but if we use static synchronized so it will lock a class (one thread can access a class at a time). More details.

What is the purpose of using javap?

The javap command disassembles a class file. The javap command displays information about the fields, constructors and methods present in a class file.

Syntax

javap fully_class_name

 

What are the ways to instantiate the Class class?

There are three ways to instantiate the Class class.

  • forName() method of Class class: The forName() method is used to load the class dynamically. It returns the instance of Class class. It should be used if you know the fully qualified name of the class. This cannot be used for primitive types.

 

  • getClass() method of Object class: It returns the instance of Class class. It should be used if you know the type. Moreover, it can be used with primitives.

 

  • the .class syntax: If a type is available, but there is no instance then it is possible to obtain a Class by appending ".class" to the name of the type. It can be used for primitive data type also.

What is a JavaBean?

JavaBean is a reusable software component written in the Java programming language, designed to be manipulated visually by a software development environment, like JBuilder or VisualAge for Java. t. A JavaBean encapsulates many objects into one object so that we can access this object from multiple places. Moreover, it provides the easy maintenance. Consider the following example to create a JavaBean class.

  1. //Employee.java  
  2. package mypack;  
  3. public class Employee implements java.io.Serializable{  
  4. private int id;  
  5. private String name;  
  6. public Employee(){}  
  7. public void setId(int id){this.id=id;}  
  8. public int getId(){return id;}  
  9. public void setName(String name){this.name=name;}  

10. public String getName(){return name;}  

11. }  

What is the purpose of using the Java bean?

According to Java white paper, it is a reusable software component. A bean encapsulates many objects into one object so that we can access this object from multiple places. Moreover, it provides the easy maintenance.

What is the return type of Class.forName() method?

The Class.forName() method returns the object of java.lang.Class object.

What is Spring?

It is a lightweight, loosely coupled and integrated framework for developing enterprise applications in java.

What is IOC and DI?

IOC (Inversion of Control) and DI (Dependency Injection) is a design pattern to provide loose coupling. It removes the dependency from the program.

Let's write a code without following IOC and DI.

  1. public class Employee{  
  2. Address address;  
  3. Employee(){  
  4. address=new Address();//creating instance  
  5. }  
  6. }  

Now, there is dependency between Employee and Address because Employee is forced to use the same address instance.

Let's write the IOC or DI code.

  1. public class Employee{  
  2. Address address;  
  3. Employee(Address address){  
  4. this.address=address;//not creating instance  
  5. }  
  6. }  

Now, there is no dependency between Employee and Address because Employee is not forced to use the same address instance. It can use any address instance.

 

What are the advantages of spring framework?

  1. Predefined Templates
  2. Loose Coupling
  3. Easy to test
  4. Lightweight
  5. Fast Development
  6. Powerful Abstraction
  7. Declarative support

More details...

 

posted @ 2020-04-26 11:51  CodingYM  阅读(225)  评论(0编辑  收藏  举报