How synchronization works in java | synchorization working concept | point to remember during java synchronization interview question

Java Synchronization concept :

Every object has a intrinsic lock or monitor lock or simply we can say monitor . A thread can enter a sychronized method only if the thread can aquire the Object's lock. Once the thread aquires the lock automatically for a synchronized method , the thread enters into that method . As only one thread can own a lock of the object at a time, no other thread can own the same lock and enter into same synchronized method and other synchronized methods in the same object. The lock is released when the thread exits the synchronized method. The lock release occurs even if the return was caused by an uncaught exception. Now other thread can acquire the same lock to execute other synchronized methods or same method. When a thread releases an intrinsic lock, a happens-before relationship is established between that action and any subsequent acquistion of the same lock to ensure the reliable communication between threads.

There are two ways in which you can use synchronization to manage your threads of execution.
1. Synchronizing methods - Managing code at the method level .
eg. public synchronized void withdraw(int amount)
{code in method.}
2. Synchronizing statements(block of code) -Managing code at the block level.
eg. synchronized (object/class) { block of code }

Synchronized Methods

For protecting shared data / resource , no need to lock the data itself, we need to synchronize the methods that access that data / resource. You can make methods of a class mutual exclusive by declaring them using the keyword synchronized . You can make all the methods or some of the methods of a class synchronized depending upon the requirements. You have to synchronize those methods only that access / modify the shared data (eg. instance variables) or resources. All reads or writes to that object's variables by a thread are visible to other threads through synchronized methods.

Consider the above sample code for bank account.

class Account
{
private int balance;
private int accountNumber;
.........
public synchronized int getBalance()
{ return balance;
}

public synchronized void withdraw(int amount)
{
........
if (balance<amount)
{
throw new RuntimeException("Amount not available");
} balance -= amount;}

public void method3()
{
// code for the method3
}
}

 The above account class has three methods . Both withdraw() and getBalance() are synchronized and method3 is not synchronized. Now only one of the synchronized methods in a class object can execute at any one time . That means either withdraw() method or getBalance() method can be executed at any one time . method3 can always be executed by a thread. Unnecessary syncronization may reduce the performance of the program

Synchronizing Statement(s) (Blocks of code)

You can synchronize a statement or a block of code without synchronizing the whole method using the syntax given below . Synchronized statements must specify the object that provides the intrinsic lock. This is more useful because you can specify particular object that benefits from synchronization of the staments . When a thread enters the block that is synchronized on any given object , no other thread can enter other synchronized blocks or methods on the same object . Syntax is
synchronized(obj)
 {
 Block of code
 }

List list = Collections.synchronizedList(new ArrayList());
The above line returns a thread-safe list backed by the specified list . If one thread changes the list while another thread is traversing it through an Iterator, it will throw ConcurrentModificationException. To stop this exceptioin, Lock the entire List when you are iterating by using the synchronized block that synchronizes on the the returned list .
//block of code synchronized on list. So when the list is modified , it can't be traversed. When the list is iterated , this list can't be modified.

 synchronized(list) {
 Iterator iter = list.iterator();
while (iter.hasNext())
 doSomething(iter.next());
 }

You can also use , private lock object that is inaccessible outside, with synchronized block instead of using synchronized methods
private final Object lock1 = new Object();
 public void inc1() {
 synchronized(lock1) {
 c1++;
 }
 }

Synchronization can be considered expensive , because

1. Synchronization leads to poor performance.
a) The JVM takes time to make ordering of synchronization actions executing in different threads.
b) When a thread enters synchronized method, it has to acquire object's lock and releases when exits the method.
c) JMM (Java Memory Model) requires that the cached values to be invalidated immediately after the lock is acquired, and writing cache values back to main memory (flushing the cache) before it is released which ensures the proper inter-thread communication . Flushing the cache frequently can be expensive
2. Synchronized method can slow down the program execution , because synchronization does not allow concurrency . Only one thread is allowed at a time to enter into synchronized methods.
3. Synchronized methods may lead to deadlock

Summary points to remember on synchronization for Interview


1. The main objective of synchronization is to ensure that when several threads want access to a single resource , only one thread can access it at any given time.
2. Each object has only one lock.
3. Instance method gets lock on the Object where as static method get locks the Class in which the method is defined
4. Final fields and Immutable objects are thread-safe that requires no synchronization.
5. Constructors cannot be synchronized
6. If an object is visible to more than one thread, all reads or writes to that object's variables need to be done through synchronized methods.
6. Reentrant Synchronization : A thread can acquire a lock that it already owns which helps to invoke a method that also contains synchronized code
7. Alternative ways of synchronization are the use of classes in the java.util.concurrent package , declaring volatile variables that ensures all threads see a consistent value for the variable
8. The volatile modifier helps for reliable communication between threads but does not suuport for mutual exclusion
9. wait() method of object that can be called from synchronized methods or synchronized block to give up the lock i.e. to suspend the current thread until the notify() or notifyAll() method is called.

Complete program to test with synchronization and without Synchronization

import java.util.Random;
class Account {
private int balance;
private int accountNumber;
public Account(int accountNumber, int balance)
{
this.accountNumber=accountNumber;
this.balance=balance;
}
public synchronized int getBalance()
{
return balance;
}

public synchronized void withdraw(int amount) {
System.out.println("Accout Number = " + accountNumber + " " + Thread.currentThread().getName() + " needs " + amount);
try
{
Thread.sleep(30);
}catch(Exception e){ }

if (balance<amount)
{
System.out.println("Available Balance is = " + balance + " which is less than required amount " + amount);
throw new RuntimeException("Amount not available");
}
balance -= amount;
System.out.println(Thread.currentThread().getName() + " Withdraws " + amount );
System.out.println( " Current balance = " + balance);
}
}

public class BankOperation1 implements Runnable {
private Account account = new Account(21120, 10000);
public static void main (String [] args) {
BankOperation1 wd = new BankOperation1();
Thread person1 = new Thread (wd) ;
Thread person2 = new Thread (wd) ;
person1.setName ("Johnson") ;
person2.setName ("Jacob") ;
person2.start () ;
person1.start () ;
}
public void run ( ) {
Random rndObj = new Random();
System.out.println("Available Balance= " + account.getBalance());
//for (int i= 1; i <= 100; i++)
//{
account.withdraw(7500) ;
//}
}
}


When I run the above code without synchronized methods , i got the below output rarely. Remove synchronized keyword from the above code for testing


The above output shows , both threads (Mr. Jacob & Mr. Jhonson) enters into withdraw () method . Both withdraws money Rs. 7500/- . and the changes made to balance variable by one thread are not communicated to other thread.

When I run the above code with synchronized methods, i got the below output every time


The above output shows , only one thread (either Mr. Jacob or Mr. Jhonson) enters into withdraw () method . The first thread is able to withdraw money Rs. 7500/- . and the changes made to balance variable by one thread is communicated to other thread.

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.