Most Asked Java Interview Question in Various Software company in year 2012

Hi Friend , i have attended  java interview at many MNC IT company in Noida ,Delhi, Gurgaon, on basis below listed java interview question which asked many times. 


1) About current project that I am working?
2) Current Role & responsibilities in current project
3) Equals&Hascode?why need to implement these methods? How to implement?
4) How will you test for Equals method using Junit?
5) What is Reflex package in java?
5) What are the Java contracts defined to implement Equals&hashcode
6) What is Synchronization? How will you implement synchronization?
7) what is TreeSet?
8) Difference between ConcurrentHashMap and Synchronized Map? what is the best way to implement?
9) What is the easiest way to implement Sorted Set
10) What are the methods in Object class?
11) Difference between String,StringBuffer,StringBuilder
12) If the same path was given to Global Forward & Action Forward in struts config xml then which one will take the priority.
13) Struts Can have Multiple Struts_Config.xml
14) Where to declare and how declare multiple Struts config xmls
15) How to transfer the bean values between multiple jsps going throw action classes.
16) What is IOC?
17) What is Dependency Injection?
18) What are kinds of Dependency injection in Spring.
19) How to define Criteria?
20) What is SessionFactory?
21) How to get session Ojbect?
22) What is ThreadLocal?
24) what is XETransaction?
25) Difference between Pessimistic Concurrency Control and Optimistic Concurrency Control?
26) Implementation of Optimistic Concurrency Control?
27) what is difference between Local Transaction and Distributed Transaction.

For Answer read www.newserverside.blogspot.com regularly

How to tune SQL query in our appliction | Performance tuning of SQL Queries


Below Point need to tune SQL Queries

  1.   Understanding of the Data, Business, and Application - it's almost impossible to fine-tune the SQl statements without having a proper understanding of the data managed by the application and the business handled by the application. The understanding of the application is of course of utmost importance. By knowing these things better, we may identify several instances where the data retrieval/modification by many SQL queries can simply be avoided as the same data might be available somewhere else, may be in the session of some other integrating application, and we can simply use that data in such cases. The better understanding will help you identify the queries which could be written better either by changing the tables involved or by establishing relationships among available table
  2.     Using realistic test data - if the application is not being tested in the development/testing environments with the volume and type of data, which the application will eventually face in the production environment, then we can't be very sure about how the SQL queries of the application will really perform in actual business scenarios. Therefore, it's important to have the realistic data for development/testing purposes as well.
  3.  Using Bind Variables, Stored Procs, and Packages - Using identical SQL statements (of course wherever applicable) will greatly improve the performance as the parsing step will get eliminated in such cases. So, we should use bind variables, stored procedures, and packages wherever possible to re-use the same parsed SQL statements.
  4. Using the indexes carefully - Having indexes on columns is the most common method of enhancing performance, but having too many of them may degrade the performance as well. So, it's very critical to decide wisely about which all columns of a table we should create indexes on. Few common guidelines are:- creating indexes on the columns which are frequently used either in WHERE clause or to join tables, avoid creating indexes on columns which are used only by functions or operators, avoid creating indexes on the columns which are required to changed quite frequently, etc.
  5. Making available the access path - the optimizer will not use an access path that uses an index only because we have created that index. We need to explicitly make that access path available to the optimizer. We may use SQL hints to do that.
  6. Using EXPLAIN PLAN and TKPROF - these tools can be used to fine tune SQL queries to a great extent. EXPLAIN PLAN explains the complete access path which will be used by the particular SQL statement during execution and the second tool TKPROF displays the actual performance statistics. Both these tools in combination can be really useful to see, change, and in turn fine-tune the SQL statements.
  7. Optimizing the WHERE clause - there are many cases where index access path of a column of the WHERE clause is not used even if the index on that column has already been created. Avoid such cases to make best use of the indexes, which will ultimately improve the performance. Some of these cases are: COLUMN_NAME IS NOT NULL (ROWID for a null is not stored by an index), COLUMN_NAME NOT IN (value1, value2, value3, ...), COLUMN_NAME != expression, COLUMN_NAME LIKE'%pattern' (whereas COLUMN_NAME LIKE 'pattern%' uses the index access path), etc. Usage of expressions or functions on indexed columns will prevent the index access path to be used. So, use them wisely!
  8. Using WHERE instead of HAVING - usage of WHERE clause may take advantage of the index defined on the column(s) used in the WHERE clause
  9.   Using the leading index columns in WHERE clause - the WHERE clause may use the complex index access path in case we specify the leading index column(s) of a complex index otherwise the WHERE clause won't use the indexed access path.
  10.   Indexed Scan vs Full Table Scan - Indexed scan is faster only if we are selcting only a few rows of a table otherwise full table scan should be preferred. It's estimated that an indexed scan is slower than a full table scan if the SQL statement is selecting more than 15% of the rows of the table. So, in all such cases use the SQL hints to force full table scan and suppress the use of pre-defined indexes. Okay... any guesses why full table scan is faster when a large percentage of rows are accessed? Because an indexed scan causes multiple reads per row accessed whereas a full table scan can read all rows contained in a block in a single logical read operation.
  11. Using ORDER BY for an indexed scan - the optimizer uses the indexed scan if the column specified in the ORDER BY clause has an index defined on it. It'll use indexed scan even if the WHERE doesn't contain that column (or even if the WHERE clause itself is missing). So, analyze if you really want an indexed scan or a full table scan and if the latter is preferred in a particular scenario then use 'FULL' SQL hint to force the full table scan.
  12.  Minimizing table passes - it normally results in a better performance for obvious reasons
  13.  Joining tables in the proper order - the order in which tables are joined normally affects the number of rows processed by that JOIN operation and hence proper ordering of tables in a JOIN operation may result in the processing of fewer rows, which will in turn improve the performance. The key to decide the proper order is to have the most restrictive filtering condition in the early phases of a multiple table JOIN. For example, in case we are using a master table and a details table then it's better to connect to the master table first to connecting to the details table first may result in more number of rows getting joined.
  14. Simple is usually faster - yeah... instead of writing a very complex SQL statement, if we break it into multiple simple SQL statements then the chances are quite high that the performance will improve. Make use of the EXPLAIN PLAN and TKPROF tools to analyze both the conditions and stick to the complex SQL only if you're very sure about its performance.
  15.  Using ROWID and ROWNUM wherever possible - these special columns can be used to improve the performance of many SQL queries. The ROWID search is the fastest for Oracle database and this luxury must be enjoyed wherever possible. ROWNUM comes really handy in the cases where we want to limit the number of rows returned.
  16. Usage of explicit cursors is better - explicit cursors perform better as the implicit cursors result in an extra fetch operation. Implicit cursosrs are opened the Oracle Server for INSERT, UPDATE, DELETE, and SELECT statements whereas the explicit cursors are opened by the writers of the query by explicitly using DECLARE, OPEN, FETCH, and CLOSE statements.
  17.  Reducing network traffic - Arrays and PL/SQL blocks can be used effectively to reduce the network traffic especially in the scenarios where a huge amount of data requires processing. For example, a single INSERT statement can insert thousands of rows if arrays are used. This will obviously result into fewer DB passes and it'll in turn improve performance by reducing the network traffic. Similarly, if we can club multiple SQL statements in a single PL/SQL block then the entire block can be sent to Oracle Server involving a single network communication only, which will eventually improve performance by reducing the network traffic.
  18. Using Oracle parallel query option - Since Oracle 8, even the queries based on indexed range scans can use this parallel query option if the index is partitioned. This feature can result in an improved performance in certain scenarios.

Java File Tutorial : How to read file line by line in Java - BufferedReader Scanner Example Tutorial

Line by Line reading in Java using BufferedReader and Scanner
There are multiple ways to read file line by line in Java. Most simple example of reading file line by line is using BufferedReader which provides method readLine() for reading file. Apart from generics, enum and varargs Java 1.5  has also introduced several new class in Java API one of the  utility class is Scanner, which can also be used to read any file line by line in Java. Though BufferedReader is available in Java from JDK 1.1,  java.util.Scanner provides more utility methods compared to BufferedReader. Scanner has method like hasNextLine() and nextLine() to facilitate line by line reading of file's contents. nextLine() returns String similar to  readLine() but scanner has more utility methods like nextInt(), nextLong() which can be used to directly read numbers from file instead of converting String to Integer or other Number classes. By the way Scanner is rather new approach for reading file and BufferedReader is the standard one. This is my 6th tutorial on Java IO,  In last couple of post we have seen creating file and directory in Java, parsing XML files using DOM and how to read properties file in Java. In this post we will focus on reading file line by line in Java using both BufferedReader and Scanner.

Reading file line by line in Java - BufferedReader Example
Java file read line by line example BufferedReader ScannerIn this example we are using BufferedReader for reading file content line by line. BufferedReader needs an InputStream which is a FileInputStream in this case and readLine() returns value of line or null if end of Stream has reached. line is terminated with line terminator e.g. \n or \r

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * BufferedReader and Scanner can be used to read line by line from any File or
 * console in Java.
 * This Java program demonstrate line by line reading using BufferedReader in Java

 */
public class BufferedReaderExample { 

    public static void main(String args[]) {
    
        //reading file line by line in Java using BufferedReader     
        FileInputStream fis = null;
        BufferedReader reader = null;
    
        try {
            fis = new FileInputStream("C:/sample.txt");
            reader = new BufferedReader(new InputStreamReader(fis));
        
            System.out.println("Reading File line by line using BufferedReader");
        
            String line = reader.readLine();
            while(line != null){
                System.out.println(line);
                line = reader.readLine();
            }         
        
        } catch (FileNotFoundException ex) {
            Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
        
        } finally {
            try {
                reader.close();
                fis.close();
            } catch (IOException ex) {
                Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
  }

Output:
Reading File line by line using BufferedReader
first line in file
second line
third line
fourth line
fifth line
last line in file


while using FileInputStream or any IO Reader don't forget to close the stream in finally block so that file descriptor associated with this operation get released. If not closed properly Java program may leak file descriptors which is a limited resource and in worst case program will not be able to open any new file. If you are Java 7 then you can use Automatic resource management or ARM blocks to let those resource automatically get closed by Java.


Reading file line by line in Java - Scanner Example
Scanner is new addition in Java 1.5 along-with several other changes like auto-boxing and has been a preferred choice for reading inputs from console. Since Scanner is able to read from InputStream , it can also be used to read from text File and it provide many utility methods to read line by line contents using nextLine() or nextInt() etc.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 * @author Javin Paul
 * Java program to read file line by line using Scanner. Scanner is a rather new
 * utility class in Java and introduced in JDK 1.5 and preferred way to read input
 * from console.
 */
public class ScannerExample {


    public static void main(String args[]) throws FileNotFoundException  {
    
       //Scanner Example - read file line by line in Java using Scanner
        FileInputStream fis = new FileInputStream("C:/sample.txt");
        Scanner scanner = new Scanner(fis);
    
        //reading file line by line using Scanner in Java
        System.out.println("Reading file line by line in Java using Scanner");
    
        while(scanner.hasNextLine()){
            System.out.println(scanner.nextLine());
        }
    
        scanner.close();
    } 
    
}

Output:
Reading file line by line in Java using Scanner
first line in file
second line
third line
fourth line
fifth line
last line in file

Java 7 : How to use string in switch case in Jdk 7 with example

Have you ever feel that String should be used in switch cases as like int and char? JDK 7 has made an important enhancement in there support of String, now you can use String in switch and case statement, No doubt String is most widely used type in Java and in my opinion they should have made this enhancement long back when they provided support for enum in java and allowed enum to be used in switch statement. In this java tutorial we will see how we can use String inside switch and case statement in JDK 7. This article is in continuation of my earlier post on JDK7 feature improved exception handling using multi cache block in Java

string and switch in jdk7 example tutorial many a times we want to switch based upon string output received from user or other part of program but before JDK7 we can't do it directly instead either we need to map those String to final integer constant or char constant to use them inside switch and case or you need to fallback on if-else statement which gets clumsy once number of cases getting increased. But now with jdk7 you can directly use String inside switch and case statement. Though it’s pretty straight forward feature let see an example of how to use String inside switch and case statement in JDK7.

Example of String in Switch in JDK7

public static void tradingOptionChooser(String trading) {
 switch (trading) {
  case "Stock Trading":
       System.out.println("Trader has selected Stock Trading option");
       break;
  case "Electronic Trading":
       System.out.println("Trader has selected Electronic Trading option");
       break;
  case "Algorithmic Trading":
       System.out.println("Trader has selected Algorithmic Trading option");
       break;
  case "Foreign exchange trading":
       System.out.println("Trader has selected Foreign exchange Trading option");
       break;
  case "commodity trading":
       System.out.println("Trader has selected commodity trading option");
       break;
 default:
       throw new IllegalArgumentException();
 }
}
Example of String in Switch prior JDK7
Now let's see how it can be done prior to JDK 7 using if-else statement:
public static void tradingOptions(String trading) {

if (trading.equals("Stock Trading")) {
System.out.println("Trader has selected Stock Trading option");

} else if (trading.equals("Electronic Trading")) {
System.out.println("Trader has selected Electronic Trading option");

} else if (trading.equals("Algorithmic Trading")) {
System.out.println("Trader has selected Algorithmic Trading option");

} else if (trading.equals("Foreign exchange trading")) {
System.out.println("Trader has selected Foreign exchange Trading option");

} else if (trading.equals("commodity trading")) {
System.out.println("Trader has selected commodity trading option");

} else {
throw new IllegalArgumentException();
}
}

Overall allowing String into switch and case statement is not a wow feature but in my opinion very useful one and definitely makes coding easier and make code more readable by either removing clumsy if-else statement. So I definitely vote plus one to JDK 7 String in switch feature and thanks to guys involved in project coin for making life easier of java developers.

You also need to ensure that your JRE must have source 1.7 otherwise if you try to run string in switch in JRE less than 7 you will get following errro

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - strings in switch are not supported in -source 1.6
  (use -source 7 or higher to enable strings in switch)
        at jdk7demo.JDK7Demo.tradingOptionChooser(JDK7Demo.java:34)
        at jdk7demo.JDK7Demo.main(JDK7Demo.java:25)

IBM WAS Tutorial : How to create profile in silent mode in websphere application server (WAS)

The following tutorial helps you to create new profile in WebSphere Application Server in websphere application server (WAS) standalone or deployment manager  (dmgr)  in linux or windows machine . You can create profile in silent mode where you are not able to access gui . Creating profile using silent mode is simple which  uses a file (response file) to supply profile creation  inputs / options such as port numbers , host name , node name , etc ... without user interaction . To configure the profile, change the options in the response file before you issue the profile creation command. . If you omit the response file ,  default options will be used to create the profile .




To create profile using default options , use the following command ,..

change to the folder

" <WAS_HOME >\bin\ProfilesCreator" 

 In Linux ,  path may be      /opt/IBM/WebSphere/AppServer /bin / ProfilesCreator 

In windows , path may be C:\...\IBM/WebSphere/AppServer /bin / ProfilesCreator    and run the following command 




 In Linux   ,   ./ pctlinux.bin -silent

 In Windows , pctWindows.exe  -silent




Now the profile is created with default port numbers (9060, 9080,..)  & node name, etc...  You can change the port numbers in the two xml files .. serverindex.xml ,  virtualhosts.xml

where virtualhosts.xml file located in the folder

/opt/IBM/WebSphere/AppServer1/profiles/AppSrv01/config/cells/virtualhosts.xml 

and serverfindex.xml file located in the folder ....

/opt/IBM/WebSphere/AppServer1/profiles/AppSrv01/config/cells/nodes//serverindex.xml

After changing the port numbers , you have to restart the WAS  server.
 To create profile with your own  options , use the following  steps

copy the existing  response file  located in the following  paths to the new file (for eg. myProfile1.txt)

1.   Product disk location (/WAS directory)

2.  Installed location  (app_server_root/bin/ProfileCreator directory)




Existing response files available in the above locations
 with WAS Express edition

 responsefile.pct.ExpressProfile.txt




with  dmgr ,

 responsefile.pct.NDdmgrProfile.txt

 responsefile.pct.NDmanagedProfile.txt

 responsefile.pct.NDstandAloneProfile.txt




Change the response file (myProfile1.txt)  with your own options such as port numbers , node name , host name , etc... and run the following command




In Linux   ,   ./ pctlinux.bin -options myProfile1.txt -silent

In Windows , pctWindows.exe -options myProfile1.txt  -silent




The minimum necessary lines in the response file with my own options  are given below ... Save  the below lines in a text file and run the above command



 -W  profilenamepanelInstallWizardBean.profileName="appSrv03"



-W profilenamepanelInstallWizardBean.isDefault="true"



-P installLocation="/opt/IBM/WebSphere/AppServer1/profiles/appServer"



-W  nodehostnamepanelInstallWizardBean.nodeName="test"



-W nodehostnamepanelInstallWizardBean.hostName="your host name"



-W pctdefaultprofileportspanelInstallWizardBean.WC_defaulthost="9083"



-W  pctdefaultprofileportspanelInstallWizardBean.WC_adminhost="9063"



-W pctdefaultprofileportspanelInstallWizardBean.WC_defaulthost_secure="9446"



-W  pctdefaultprofileportspanelInstallWizardBean.WC_adminhost_secure="9046"



-W pctdefaultprofileportspanelInstallWizardBean.BOOTSTRAP_ADDRESS="2812"



-W  pctdefaultprofileportspanelInstallWizardBean.SOAP_CONNECTOR_ADDRESS="8883"



-W pctdefaultprofileportspanelInstallWizardBean.SAS_SSL_SERVERAUTH_LISTENER_ADDRESS="9404"



-W  pctdefaultprofileportspanelInstallWizardBean.CSIV2_SSL_SERVERAUTH_LISTENER_ADDRESS="9406"



-W  pctdefaultprofileportspanelInstallWizardBean.CSIV2_SSL_MUTUALAUTH_LISTENER_ADDRESS="9405"



-W pctdefaultprofileportspanelInstallWizardBean.ORB_LISTENER_ADDRESS="9103"



-W  pctdefaultprofileportspanelInstallWizardBean.DCS_UNICAST_ADDRESS="9356"



-W pctdefaultprofileportspanelInstallWizardBean.SIB_ENDPOINT_ADDRESS="7279"



-W  pctdefaultprofileportspanelInstallWizardBean.SIB_ENDPOINT_SECURE_ADDRESS="7289"



-W pctdefaultprofileportspanelInstallWizardBean.SIB_MQ_ENDPOINT_ADDRESS="5561"



-W  pctdefaultprofileportspanelInstallWizardBean.SIB_MQ_ENDPOINT_SECURE_ADDRESS="5581"



-W  winservicepanelInstallWizardBean.winServiceQuery="true"



-W  winservicepanelInstallWizardBean.accountType="localsystem"



-W winservicepanelInstallWizardBean.userName="test"



-W  winservicepanelInstallWizardBean.password="test123"



-W winservicepanelInstallWizardBean.startupType="manual"



-W  profiletypepanelInstallWizardBean.selection="default"


In the above lines ,

Profile name is  appSrv03

profile creation location is  "/opt/IBM/WebSphere/AppServer1/profiles/appServer"

WC_defaulthost="9083"  - for accessing applications  , default port is 9080

WC_adminhost="9063 - for accessing ibm admin console , default port is 9060 ,  for https (ssl) , default port is 9043

nodeName="test" - node name is test

hostName="myOwnHost" - host name is myOwnHost

Hibernate Interview question : Difference between get and load in Hibernate

get vs load in Hibernate
Difference between get and load method in Hibernate is a one of the most popular question asked in Hibernate and spring interviews. Hibernate Session  class provides two method to access object e.g. session.get() and session.load() both looked quite similar to each other but there are subtle difference between load and get method which can affect performance of application. Main difference between get() vs load method is that get() involves database hit if object doesn't exists in Session Cache and returns a fully initialized object which may involve several database call while load method can return proxy in place and only initialize the object or hit the database if any method other than getId() is called on persistent or entity object. This lazy initialization can save couple of database round-trip which result in better performance. By the way there are many articles on interview questions in Java, you can use search button on top left to find them. Some of them like 20 design pattern interview questions and 10 Singleton pattern questions are my favorites, you may also like. Coming back to article, you can find more difference between load and get in rest of this article in point format but this is the one which really makes difference while comparing both of them. If you look at how get and load gets called its pretty identical.

Difference between get and load method
Here are few differences between get and load method in Hibernate.

1. Behavior when Object is not found in Session Cache
Apart from performance this is another difference between get and load which is worth remembering. get method of Hibernate Session class returns null if object is not found in cache as well as on database while load() method throws ObjectNotFoundException if object is not found on cache as well as on database but never return null.

2. Database hit
Get method always hit database while load() method may not always hit the database, depending upon which method is called.

3. Proxy
Get method never returns a proxy, it either returns null or fully initialized Object, while load() method may return proxy, which is the object with ID but without initializing other properties, which is lazily initialized. If you are just using returned object for creating relationship and only need Id then load() is the way to go.

4. Performance
By far most important difference between get and load in my opinion. get method will return a completely initialized object if  Object is not on the cache but exists on Database, which may involve multiple round-trips to database based upon object relational mappings while load() method of Hibernate can return a proxy which can be initialized on demand (lazy initialization) when a non identifier method is accessed. Due to above reason use of load method will result in slightly better performance, but there is a caveat that proxy object will throw ObjectNotFoundException later if corresponding row doesn’t exists in database, instead of failing immediately so not a fail fast behavior.

5. load method exists prior to get method which is added on user request.

When to use Session get() and load() in Hibernate
get vs load hibernate interview questionSo far we have discussed how get and load are different to each other and how they can affect performance of your web application, after having this information in our kitty we can see some best practices to get most of load and get together. This section suggest some scenario which help you when to use get and load in Hibernate.

1. Use get method to determine if an instance exists or not because it can return null if instance doesn’t exists in cache and database and use load method to retrieve instance only if you think that instance should exists and non availability is an error condition.

2.  As stated in difference number 2 between get and load in Hibernate. get() method could suffer performance penalty if only identifier method like getId()  is accessed. So consider using load method  if  your code doesn't access any method other than identifier or you are OK with lazy initialization of object, if persistent object is not in Session Cache because load() can return proxy.

How to call get records in Hibernate using get and load method
If you look at below code , there is not much difference on calling get() and load() method, though both are overloaded now and can accept few more parameters but the primary methods looks exactly identical. It’s there behavior which makes them different.

//Example of calling get method of Hiberante Session class
Session session = SessionFactory.getCurrentSession();
Employee Employee = (Employee) session.get(Employee.class, EmployeeID);

//Example of calling load method of Hiberante Session
Session session = SessionFactory.getCurrentSession();
Employee Employee = (Employee) session.load(Employee.class, EmployeeID);


That’s all on difference between get and load in Hibernate. No doubt Hibernate is a great tool for Object relational mapping but knowing this subtle differences can greatly help to improver performance of your J2EE application, apart from practical reason get vs load method is also frequently asked questions in Hibernate interview, so familiarity with differences between load and get certainly helps.

Most asked 15 java threading interview questions asked in Investment banks

f you are going for java interview on any Investment bank expect lots of muti-threading interview questions on your way. Multi-threading is a favorite topics on Investment banking specially on electronic trading development and they grill candidate on many confusing java thread interview questions. They just want to ensure that the guy has solid knowledge of multi-threading and concurrent programming in java because most of them are in business of performance. High volume low latency Electronic trading System which is used for Direct to Market (DMA) trading is usually concurrent in nature. These are my favorite thread interview questions on java asked on different on different time. I am not providing answer of these thread interview questions but I will give you hint whenever possible. Answer of these java thread interview questions can be found by doing Google.

Java Multi-threading Interview questions answers:
More important is to understand the concept behind these multi-threading questions simply mugging the answers of thread interview questions is not going to help because there would be a lot of follow-up questions based upon your answer and if you haven't master the particular thread topic it would be difficult. Threading in Java is very interesting topic even more after Java 5 which has added lot of concurrency classes and now days interview on java thread are mostly focus around this new concurrent utilities like Executor framework, Countdown Latch, Atomic classes, Re-entrant and ReadWriteLock and Concurrent Collection classes.

15 Java Thread Interview Questions and answers
1) You have thread T1, T2 and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2?
java thread interview questionsThis thread interview questions is mostly asked in first round or phone screening round of interview and purpose of this multi-threading question is to check whether candidate is familiar with concept of "join" method or not. Answer of this multi-threading questions is simple it can be achieved by using join method of Thread class.


2) What is the advantage of new Lock interface over synchronized block in Java? You need to implement a high performance cache which allows multiple reader but single writer to keep the integrity how will you implement it?
The major advantage of lock interfaces on multi-threaded and concurrent programming is they provide two separate lock for reading and writing which enables you to write high performance data structure like concurrenthashmp and conditional blocking. This java threads interview question is getting increasingly popular and more and more follow-up questions come based upon answer of interviewee. I would strongly suggest reading Locks before appearing for any java multi-threading interview because now days Its  heavily used to build cache for electronic trading system on client and exchange connectivity space.



3) What are differences between wait and sleep method in java?
Another classic interview question on java thread mostly asked in phone interview. Only major difference is wait release the lock or monitor while sleep doesn't release any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution.


4) Write code to implement blocking queue in Java?
This java multi-threading  interview question servers many purpose , it checks whether candidate can actually write java code using thread or not, it sees how good interviewee is on understanding scenarios of multi-threading and you can ask lot of follow-up question based upon his code. If he uses wait() and notify() method to implement blocking queue, Once interviewee successfully writes it  you can ask him to write it again using new java 5 concurrent classes.



5) Write code to solve the Produce consumer problem in Java?
Similar to above questions on thread but more classic in nature, some time interviewer ask follow up questions as what happen if you have multiple Producer and single consumer or vice-versa , so be prepare for surprises. Some time they even ask to implement solution of dining philosopher problem as well.

6) Write a program which will result in deadlock? How will you fix deadlock in Java?
This is my favorite java thread interview question because even though deadlock is quite common while writing multi-threaded concurrent program many candidates not able to write deadlock free code and they simply struggle. Just ask them you have n resources and n thread and to complete an operation you require all resources. Here n can be replace with 2 for simplest case and higher number to make question more intimidating. To read more about deadlock in java  see the link.


7) What is atomic operation? What are atomic operations in Java?
Simple java thread interview questions, another follow-up is do you need to synchronized an atomic operation? :) You can read more about java synchronization here.


8) What is volatile keyword in Java? How to use it? How is it different from synchronized method in Java?
Thread questions based on volatile keyword in Java has become more popular after changes made on it on Java 5 and Java memory model. It’s good to prepare well about how volatility ensures visibility, ordering and consistency.


9) What is race condition? How will you find and solve race condition?
Another classic java threading interview questions and mostly interviewer grill on recent race condition you have faced and how did you solve it and some time they will write sample code and ask you detect race condition. In my opinion this is one of the best java thread interview question and can really test the candidate's experience on solving race condition or writing code which is free of data race or any other race condition. Best book to get mastery of this topic is "Concurrency practices in Java'".


10) How will you take thread dump in Java? How will you analyze Thread dump?
In UNIX you can use kill -3 and then thread dump will print on log on windows you can use "CTRL+Break". Rather simple and focus thread interview question but can get tricky if he ask how you analyze it.


11) Why we call start() method which in turns calls run method, why not we directly call run method ?
Another classic java multi-threading interview question This was my original doubt when I started programming in thread. Now days mostly asked in phone interview or first round of interview at mid and junior level java interviews.


12) How will you awake a blocked thread in java?
This is tricky question blocking can result on many ways, if thread is blocked on IO then I don't think there is a way to interrupt the thread, let me know if there is any, on the other hand if thread is blocked due to result of calling wait(), sleep() or join() method you can interrupt the thread and it will awake by throwing Interrupted Exception.


13) What is difference between CyclicBarriar and Countdown Latch in Java ?
New java thread interview questions mostly to check familiarity with JDK 5 concurrent packages.


14) What is immutable object? How does it help on writing concurrent application?
Another classic interview questions on multi-threading, not directly related to thread but indirectly helps a lot. This java interview question can become more tricky if ask you to write an immutable class or ask you Why String is immutable in Java as follow-up.


15) What are some common problems you have faced in multi-threading environment? How did you resolve it?
Memory-interference, race conditions, deadlock, live lock and starvation are example of some problems comes in multi-threading and concurrent programming. There is no end of problem if you get it wrong and they will be hard to detect and debug. This is mostly experienced based interview question on java thread instead of fact based.