Google

Feb 27, 2014

Debugging Java Class loading issues

"I thought that I was using my application package version of a library but apparently my application server (e.g. Weblogic, JBoss) has already loaded an older version of this-library-issue" 

These issues normally arise when there are certain classes which are packaged along with Application Server as part of common libraries and the same set of classes are also present in your Application package as well (normally inside WEB-INF/lib folder of the application). The reasons for the problem lies with how the class loading works in any Application Server.

A common question many developers ask is that

Where on the file system was my Java class loaded from?

Here are some tips and steps to troubleshoot Java class loading issues.

1. -verbose:class option in your JVM. With the -verbose option all the classes that are loaded are listed, along with the JAR file or directory from which they were loaded. The "class" output shows additional information, such as when superclasses are being loaded, and when static initializers are being run.

2. Creating a Java dump and analyzing the Java dump for class loading issues. The Java dumps are created under following circumstances.
  • When a fatal native JVM error.
  • When the JVM runs out of heaps memory space.
  • When a signal is sent to the JVM (e.g. Control-Break is pressed on Windows, Control-\ on Linux, or kill -3 on Unix)
There are tools like jstack, jmap, hprof, and Eclipse Memory Analyzer (MAT) to analyze the Java dumps.

3.  Some of the libraries provide API to list the version number. For example, The Eclipse link MOXy library provides a method as shown below.

  PrintWriter out = response.getWriter();
  out.println("<html>");
  out.println("<body>");
  out.println("<h1>Simple</h1>");
  out.println(org.eclipse.persistence.Version.getVersion());
  out.println("</body>");
  out.println("</html>");
 

4.  The org.jboss.test.util.Debug class has a method  displayClassInfo(Class clazz, StringBuffer results) to display the loaded class details. This is done programmatically. What this class essentially does is

    


URL loc = MyClass.class.getProtectionDomain().getCodeSource().getLocation();


 

5. The http://www.findjar.com is an onlime search engine that can list possible jar files in which a particular class file like java.sql.Connection can be found.




6. Finally, using the Unix find and grep commands to list the jar files that has a given class file like "Connection".

 


find . -name '*.jar' -print0 |  xargs -0 -I '{}' sh -c 'jar tf {} | grep Connection.class &&  echo {}' 



You may also like

Labels: ,

Feb 25, 2014

Troubleshooting Java classloader or class loading issues -- JBoss example

Every Java developer faces the following issue from time to time.

"I thought that I was using my application package version of a library but apparently my application server (e.g. Weblogic, JBoss) has already loaded an older version of this-library-issue"

These issues normally arise when there are certain classes which are packaged along with Application Server as part of common libraries and the same set of classes are also present in our Application package as well (normally inside WEB-INF/lib folder of the application). The reasons for the problem lies with how the class loading works in any Application Server. Different Application Servers provide different mechanisms to deal with this problem. We have already looked at how to deal with this in Weblogic application server.

In JBoss 4.x versions, you need to turn off the PARENT_FIRST delegation mode in its jboss-web.xml descriptor file.


<jboss-web>
    <!--
      Sets the isolation scope for the WAR. We are now using a parent LAST policy for the war classloader.
      Meaning that classes/jars in the war take precedence over those provided by the EAr & App Server. 
    -->
 <loader-repository>
  maya.macquarie.com:loader=my-webservices.war
  <loader-repository-config>java2ParentDelegation=false</loader-repository-config>
 </loader-repository>
</jboss-web>

In JBoss 5 on wards, you need to have a jboss-classloading.xml in my_app.ear/META-INF as shown below

<classloading xmlns="urn:jboss:classloading:1.0"
            domain="my_app.ear"
            export-all="NON_EMPTY"
            import-all="true"
            parent-first="false">
</classloading>


  • by setting the domain, we are specifing that the my_app.ear application participate in its own domain my_app.ear.
  • by setting parent-first to false, we are essentially declaring that EARs classes be preferred over JBoss’s

JBoss AS 7 follows a real modular approach deprecating all earlier approaches. The server bootstrap libraries are now located at the root of the application server. The jboss-deployment-structure.xml needs to be placed within the META-INF folder of the EAR or inside WEB-INF of your war file.

<jboss-deployment-structure>
  <sub-deployment name="my_app.war">
    <dependencies>
      <module name="org.apache.log4j" />
    </dependencies>
  </sub-deployment>
</jboss-deployment-structure>

You can apply exclusions

<jboss-deployment-structure>
  <deployment>
    <exclusions>
      <module name="javax.faces.api" />
      <module name="com.sun.jsf-impl" />
    </exclusions>
    <dependencies>
      <module name="javax.faces.api" slot="2.0"/>
      <module name="com.sun.jsf-impl" slot="2.0"/>
    </dependencies>
  </deployment>
</jboss-deployment-structure>


This is only a general discussion. Please refer to the relevant JBoss documentation for more options and appropriate solutions.

Labels: ,

Feb 24, 2014

Troubleshooting Java classloader or class loading issues -- Weblogic example

Every Java developer faces the following issue from time to time.

"I thought that I was using my application package version of a library but apparently my application server (e.g. Weblogic, JBoss) has already loaded an older version of this-library-issue"

These issues normally arise when there are certain classes which are packaged along with Application Server as part of common libraries and the same set of classes are also present in our Application package as well (normally inside WEB-INF/lib folder of the application). The reasons for the problem lies with how the class loading works in any Application Server. Different Application Servers provide different mechanisms to deal with this problem. 

Recently I faced the similar issue with loading my MOXy libraries for marshaling and marshaling XML to and from Java objects. Troubleshooting these issues could be tricky. and luckily the eclipse link MOXy library had a org.eclipse.persistence.Version.getVersion( ), which prints the version of the library used. In my case, an older version was used from the Weblogic lib directory, ignoring the later version packed in my war or ear package.

Solving it when you deploy a war file in Weblogic server.

The web logic specific web deployment descriptor file weblogic.xml file shown below hinting weblogic to use the jar libraries included the WEB-INF/lib for the listed packages like org.eclipse.persistence.*.



<?xml version="1.0" encoding="UTF-8"?>
<weblogic-web-app xmlns="http://xmlns.oracle.com/weblogic/weblogic-web-app" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd http://xmlns.oracle.com/weblogic/weblogic-web-app http://xmlns.oracle.com/weblogic/weblogic-web-app/1.4/weblogic-web-app.xsd">

 <context-root>wrapng</context-root>

 <container-descriptor>
  <prefer-application-packages>
         <package-name>javax.el.*</package-name>
         <package-name>com.sun.el.*</package-name>
         <package-name>javax.faces.*</package-name>
   <package-name>com.sun.faces.*</package-name>
   <package-name>org.joda.*</package-name>
   <package-name>org.apache.*</package-name>
      <package-name>antlr.*</package-name>
      <package-name>com.sun.xml.bind.*</package-name>
   <package-name>javax.servlet.jsp.jstl.*</package-name>
   <package-name>org.eclipse.persistence.*</package-name>
     </prefer-application-packages>
 </container-descriptor>
 
 <fast-swap>
  <enabled>false</enabled>
 </fast-swap>
 
 <jsp-descriptor>
  <compress-html-template>true</compress-html-template>
 </jsp-descriptor>
 
</weblogic-web-app>


Solving it when you deploy an ear file in Weblogic server.

Similarly, if you have an ear file, and the the library is packaged within /lib folder. The ear descriptor file weblogic-application.xml  will look like

<?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-application xmlns:wls="http://www.bea.com/ns/weblogic/weblogic-application" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
   http://java.sun.com/xml/ns/javaee/javaee_5.xsd 
   http://www.bea.com/ns/weblogic/weblogic-application 
   http://www.bea.com/ns/weblogic/weblogic-application/1.0/weblogic-application.xsd">
 <wls:application-param>
  <wls:param-name>webapp.encoding.default</wls:param-name>
  <wls:param-value>UTF-8</wls:param-value>
 </wls:application-param>
 
 <wls:prefer-application-packages>
        <wls:package-name>antlr.*</wls:package-name>
        <wls:package-name>org.eclipse.persistence.*</wls:package-name>
    </wls:prefer-application-packages>
 
</wls:weblogic-application>



Refer to Weblogic documentation for other options like "prefer-web-inf-classes" element. 

Labels: ,

Feb 23, 2014

Top 20 Java technical interview questions and answers for experienced Java developers -- Part 4

Java Interview Questions and Answers

1-5 for experienced developers 6-10 for experienced developers 11-16 for experienced developers 17-20 for experienced developers

Q17. Can you explain singleton and prototype bean scopes in Spring framework? Which one is the default? Which one is thread-safe?
A17. Understanding Spring bean scopes - Singleton Vs Protype

After Spring, the most popular third-party framework is Hibernate.

Q18. Can you explain hibernate object states? Also, explain hibernate objects life cycle?
A18. 

Persistent objects and collections are short lived single threaded objects, which store the persistent state. These objects  synchronize their state with the database depending on your flush strategy (i.e. auto-flush where as soon as setXXX() method is called or an item is removed from a Set, List  etc or define your own synchronization points with session.flush(), transaction.commit() calls). If you remove an item  from a persistent collection like a Set, it will be removed from the database either immediately or when flush() or commit() is called depending on your flush strategy. They are Plain Old Java Objects (POJOs) and are currently associated with a session. As soon as the associated session is closed, persistent objects become detached objects and are free to use directly as data transfer objects in any application layers like business layer, presentation layer etc.  

Detached objects and collections are instances of persistent objects that were associated with a session but currently not associated with a session. These objects can be freely used as Data Transfer Objects without having any impact on your database. Detached objects can be later on attached to another session by calling methods like session.update(), session.saveOrUpdate() etc. and become persistent objects.

Transient objects and collections are instances of persistent objects that were never associated with a session. These objects can be freely used as Data Transfer Objects without having any impact on your database. Transient objects become persistent objects when associated to a session by calling methods like session.save( ), session.persist( )  etc.



Q19. Why use JAXB in your Java project?
A19. JAXB interview questions and answers.

If the organization you are being interviewed for is using an agile methodology, then you will be probed on agile development practices.

Q20a. What are the pros and cons of agile development methodology
A20a.  Pros and cons of agile development methodology.

Q20b. What is the difference between agile theme, epic and story?
A20b. Understanding theme, epic, and story



Java Interview Questions and Answers

1-5 for experienced developers 6-10 for experienced developers 11-16 for experienced developers 17-20 for experienced developers

Labels: , ,

Top 20 Java technical interview questions and answers for experienced Java developers - part 2

Java Interview Questions and Answers

1-5 for experienced developers 6-10 for experienced developers 11-16 for experienced developers 17-20 for experienced developers

Q6. How would you go about designing a car parking station?
A6.

Map out the requirements:
  • The car park needs to cater for different types of car parks like regular, handicapped, and compact.
  • It should keep track of empty and filled spaces.
  • It should also cater for valet parking.
Map out the classes that would be required. Use a UML class diagram. Here are some points to get started.
  • A CarPark class to represent a parking station.
  • A ParkingSpace can be an abstract class or an interface to represent a parking space, and RegularParkingSpace, HandicappedParkingSpace, CompactParkingSpace, etc are subtypes of a ParkingSpace. This means a RegularParkingSpace is a ParkingSpace.
  • A CarPark has a (i.e. composition) finite number of ParkingSpaces. A CarPark also keeps track of all the parking spaces and a separate list of all the vacant parking spaces.
  • A Vehicle class uses a (i.e. delegation) ParkingSpace.  The Vehicle class will hold attributes using enum classes like  VehicleType and ParkingType. The vehicle types could be Compact, Regular, and Handicapped. The parking types could be Self or Valet. Depending on the requirements, the self or valet types could be designed as subtypes of the Vehicle class.


Q7: Can you design the classes that represent a restaurant?
A7: Very popular. Good understanding of OO design is vital to job interview success. Learn the SOLID design principles, know why you favor composition over inheritance, and don't under estimate the power of coding to interface.
  • Java OO Interview Questions and Answers. A step-by-step tutorial explaining how you would go about designing your classes. The "Core Java Career Essentials" PDF covers more examples on SOLID design principles with working code.

How would you go about identifying thread safety issues in an application? How would you go about identifying memory leaks issues? How would you go about identifying performance issues?, etc to judge your experience. I am yet to work on a project that didn't face problems relating to thread safety, memory leaks, and performance issues. Hence, it really pays to market your skills and experience in fixing issues relating to these common challenges.


Q8. How will you go about fixing memory leaks in Java?
A8. Again, a very common problem, and a thorough answer will go a long way in securing your next Java job.

Q9: How will you go about fixing performance issues in Java?
A9:
  • Detecting performance issues in Java. A basic tutorial covering -- how to detect performance issues.
  • Also, refer to the JMeter tutorials in this blog as to learn how you can put load on your application to simulate concurrent users.

Q10: How will you go about detecting and fixing thread-safety issues in Java?
A10: Debugging concurrency issues and fixing any thread starvation, dead lock, and contention requires skills and experience to identify and reproduce these hard to resolve issues. Here are some techniques to detect concurrency issues.
  • Manually reviewing the code for any obvious thread-safety issues. There are static analysis tools like Sonar, ThreadCheck, etc for catching concurrency bugs at compile-time by analyzing their byte code.
  • List all possible causes and add extensive log statements and write test cases to prove or disprove your theories.
  • Thread dumps are very useful for diagnosing synchronization problems such as deadlocks. The trick is to take 5 or 6 sets of thread dumps at an interval of 5 seconds between each to have a log file that has 25 to 30 seconds worth of runtime action. For thread dumps, use kill -3 in Unix and CTRL+BREAK in Windows. There are tools like Thread Dump Analyzer (TDA), Samurai, etc. to derive useful information from the thread dumps to find where the problem is. For example, Samurai colors idle threads in grey, blocked threads in red, and running threads in green. You must pay more attention to those red threads.
  • There are tools like JDB (i.e. Java DeBugger) where a “watch” can be set up on the suspected variable. When ever the application is modifying that variable, a thread dump will be printed.
  • There are dynamic analysis tools like jstack and JConsole, which is a JMX compliant GUI tool to get a thread dump on the fly. The JConsole GUI tool does have handy features like “detect deadlock” button to perform deadlock detection operations and ability to inspect the threads and objects in error states. Similar tools are available for other languages as well.

Q. What is the difference between mutex and semaphores? What problem do they solve?
A.

Example 1: A trading system creates a buy order and places it in a queue, and a separate consumer thread picks up the order and sends it to the stock exchange. A typical producer and consumer scenario.

Example 2: If you want to recursively traverse through nested folders and spawn a number of worker threads to move the html files found to a destination folder and increment the semaphore permits with a release( ) method call. A separate thread will wait with the acquire(numberOfPermits) to acquire all the released permits before start archiving (i.e. zipping up) those files.

Example 3: A counter that keeps track of the number of active logged in users by incrementing the count when users log in and decrementing the count when the users log out.

Mutex and semaphores are used to solve producer and consumer synchroniztion scenarios outline above.. 

Q. Can you write code to demonstrate deadlock in Java?
A. Creating a deadlock in Java

Q. Can you give some examples of thread racing conditions you had experienced?
A. Thread racing conditions and atomic operations. 




Java Interview Questions and Answers

1-5 for experienced developers 6-10 for experienced developers 11-16 for experienced developers 17-20 for experienced developers

Labels: , ,

Feb 20, 2014

Database interview questions - triggers

The post entitled Database interview questions and answers covered some trigger based questions like
  • When to not use a trigger?
  • Where to use a trigger?
Triggers give you control just before data is changed and just after the data is changed. This allows for:
  • Auditing. 
  • Validation and business security checking if so is desired. Because of this type of control, you can do tasks such as column formatting before and after inserts into database.

In this post, I will give an example of a trigger SQL code for Sybase database.

The following trigger compares the ReportForecastId values from the inserted table with those from the ReportForecast table. When you insert a new foreign key row, make sure the foreign key matches a primary key. The trigger should check for joins between the inserted rows (using the inserted table) and the rows in the primary key table, and then roll back any inserts of foreign keys that do not match a key in the primary key table.



use my_schema
go

setuser 'dbo'
go

IF OBJECT_ID('dbo.ReportForecast_I') IS NOT NULL
BEGIN
    DROP TRIGGER dbo.ReportForecast_I
    IF OBJECT_ID('dbo.ReportForecast_I') IS NOT NULL
        PRINT '<<< FAILED DROPPING TRIGGER dbo.ReportForecast_I >>>'
    ELSE
        PRINT '<<< DROPPED TRIGGER dbo.ReportForecast_I >>>'
END
go

CREATE TRIGGER ReportForecast_I ON ReportForecast FOR INSERT AS

BEGIN
 DECLARE  @numrows int,
  @nullcnt int,
  @validcnt int,
  @insReportForecastId numeric(9,0),
  @errno   int,
  @errmsg  varchar(255),
  @ValidateCode CdStd

 SELECT @numrows = @@rowcount
 SELECT @errno = @@error      

 IF @numrows = 0
  RETURN
 /* Sybase bug allows triggers to be called after error - we rollback */
 IF @errno!=0
 BEGIN
  SELECT @errno = 997
  SELECT @errmsg = " should not have fired. Rollback"
  GOTO error
 END /* of Header */

 /***** Start of MAIN BODY *****/ 

 /* All Code Table Validations Go Here*/ 

 /* All Parent-Child Relationship Checks Go Here */ 
 
 
 


 /* Now, Depending on what operation we are going to perform we will differentiate between them like
 ** 'I' for inssert, 'U'  for update, and 'D' for delete . The audits are essentially the same but there
    */
 IF OBJECT_ID('mydb..ReportForecast_Audit') IS NOT NULL
 BEGIN 
  INSERT INTO mydb..ReportForecast_Audit (
   Audit_ModifiedDtTm,
   Audit_ModifiedBy,
   Audit_OperationType,
   ReportForecastId, 
   InactiveFlag, 
   CreatedDtTm, 
   ModifiedDtTm, 
   ModifiedBy, 
   Timestamp)
  SELECT getdate(), 
   suser_name(),
   'I',
   ReportForecast.ReportForecastId, 
   ReportForecast.InactiveFlag, 
   ReportForecast.CreatedDtTm, 
   ReportForecast.ModifiedDtTm, 
   ReportForecast.ModifiedBy, 
   ReportForecast.Timestamp
  FROM ReportForecast, inserted
  WHERE ReportForecast.ReportForecastId = inserted.ReportForecastId

  SELECT @validcnt = @@rowcount, @errno = @@error
  IF @validcnt != @numrows or @errno != 0
  BEGIN
   SELECT @errno = 998
   SELECT @errmsg = 'Error writing to audit table (ReportForecast_Audit).'
   GOTO error
  END  
 END 
 
 
 
 RETURN
error:
 SELECT @errmsg = 'ReportForecast_I: ' + @errmsg
     RAISERROR @errno @errmsg
     ROLLBACK TRANSACTION
END
go
IF OBJECT_ID('dbo.ReportForecast_I') IS NOT NULL
    PRINT '<<< CREATED TRIGGER dbo.ReportForecast_I >>>'
ELSE
    PRINT '<<< FAILED CREATING TRIGGER dbo.ReportForecast_I >>>'
go

setuser
go




Labels:

Feb 19, 2014

Spring lookup-method injection to inject prototype scoped bean into a singleton bean

This post extends Tutorial to understand Spring scopes -- singleton Vs prototype.

Step 0: You need asm and cgilib libraries in addition to Spring libraries.



Step 1: define the Dao (Data Access Object) interface.


package com.mycompany.understanding.spring;

public interface MyDao {
 abstract void printData();
}

Step 2: Define the Dao implementation.

package com.mycompany.understanding.spring;

public class MyDaoImpl implements MyDao {

 @Override
 public void printData() {
  System.out.println("printing data"); 
  System.out.println(this);
 }
}


Step 3: Define the service interface.

package com.mycompany.understanding.spring;

public interface MyService {
 abstract void performTask();
}

Step 4: Define the service implementation. Note that the class is abstract as Spring will decorate this class with cgilib.

package com.mycompany.understanding.spring;

public abstract class MyServiceImpl implements MyService {

 protected abstract MyDao createMyDao();

 @Override
 public void performTask() {
  System.out.println("Performing tasks .............");
  createMyDao().printData();
 }
}

Step 5: The spring context file applicationContext.xml that wires up dao and service. Take note of the "lookup-method".

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="myDaoDef" class="com.mycompany.understanding.spring.MyDaoImpl" scope="prototype"/>
    
    <bean id="myServiceDef" class="com.mycompany.understanding.spring.MyServiceImpl" scope="singleton"> 
       <lookup-method name="createMyDao" bean="myDaoDef" /> 
    </bean>

</beans>

Step 6: Executable main class.

package com.mycompany.understanding.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyMainApp {
 
 public static void main(String[] args) {
  ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  for (int i = 0; i <3; i++) {
   MyService service = (MyService) applicationContext.getBean("myServiceDef");
   System.out.println(service);
   service.performTask();
  }
 }
}

Output if you run the above class

com.mycompany.understanding.spring.MyServiceImpl$$EnhancerByCGLIB$$35dfd4bb@750efc01
Performing tasks .............
printing data
com.mycompany.understanding.spring.MyDaoImpl@2ac2e1b1
com.mycompany.understanding.spring.MyServiceImpl$$EnhancerByCGLIB$$35dfd4bb@750efc01
Performing tasks .............
printing data
com.mycompany.understanding.spring.MyDaoImpl@606f4165
com.mycompany.understanding.spring.MyServiceImpl$$EnhancerByCGLIB$$35dfd4bb@750efc01
Performing tasks .............
printing data
com.mycompany.understanding.spring.MyDaoImpl@282e7f59


Single instance of service has 3 separate instances of  Dao.

Labels: ,

Feb 17, 2014

Tutorial: Understanding Spring scopes -- Singleton Vs Prototype

This posts extends Understanding Spring scopes -- Singleton Vs Prototype.

Step 0: Spring Jar files required. You can use maven or download and add to the classpath.



Step 1: Define the Java interface for Dao class.


package com.mycompany.understanding.spring;

public interface MyDao {
 abstract void printData();
}


Step 2: Define the Dao implementation.

package com.mycompany.understanding.spring;

public class MyDaoImpl implements MyDao {

 @Override
 public void printData() {
  System.out.println("printing data"); 
  System.out.println(this);
 }

}

Step 3: Define the Service interface.

package com.mycompany.understanding.spring;

public interface MyService {
 abstract void performTask();
}

Step 4:  Define the Service implementation into which the Dao implementation gets injected.

package com.mycompany.understanding.spring;

public class MyServiceImpl implements MyService {

 private MyDao myDao;
 
 public MyServiceImpl(MyDao myDao) {
  this.myDao = myDao;
 }

 @Override
 public void performTask() {
  System.out.println("Performing tasks .............");
  myDao.printData();
 }
}






Step 5: Use Spring context file  applicationContext.xml to wire up the dependencies. Note that both beans are defined as singleton, which is the default.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="myDaoDef" class="com.mycompany.understanding.spring.MyDaoImpl" scope="singleton"/>
    
    <bean id="myServiceDef" class="com.mycompany.understanding.spring.MyServiceImpl" scope="singleton"> 
       <constructor-arg name="myDao" ref="myDaoDef" /> 
    </bean>

</beans>


Step 6:  The runnable main class. The applicationContext.xml is bootstrapped here.

package com.mycompany.understanding.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyMainApp {
 
 public static void main(String[] args) {
  ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  for (int i = 0; i <3; i++) {
   MyService service = (MyService) applicationContext.getBean("myServiceDef");
   System.out.println(service);
   service.performTask();
  }
 }
}

Step 7: Running the main class and comparing the results with different scopes. The for loop was created to instantiate more than one bean. Look at the memory address of the beans printed to see how many instances are created.

1.When both beans are singleton:

com.mycompany.understanding.spring.MyServiceImpl@7188eb7
Performing tasks .............
printing data
com.mycompany.understanding.spring.MyDaoImpl@5d419404
com.mycompany.understanding.spring.MyServiceImpl@7188eb7
Performing tasks .............
printing data
com.mycompany.understanding.spring.MyDaoImpl@5d419404
com.mycompany.understanding.spring.MyServiceImpl@7188eb7
Performing tasks .............
printing data
com.mycompany.understanding.spring.MyDaoImpl@5d419404

Only MyDaoImpl@5d419404 and MyServiceImpl@7188eb7 are created.

2. When both beans are prototypes: now change both scopes to "prototype" in the applicationContext.xml and retrun.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="myDaoDef" class="com.mycompany.understanding.spring.MyDaoImpl" scope="prototype"/>
    
    <bean id="myServiceDef" class="com.mycompany.understanding.spring.MyServiceImpl" scope="prototype"> 
       <constructor-arg name="myDao" ref="myDaoDef" /> 
    </bean>

</beans>


You can see 3 instances of service and 3 instances of Dao are created.

com.mycompany.understanding.spring.MyServiceImpl@64c53235
Performing tasks .............
printing data
com.mycompany.understanding.spring.MyDaoImpl@4e636942
com.mycompany.understanding.spring.MyServiceImpl@8dc488c
Performing tasks .............
printing data
com.mycompany.understanding.spring.MyDaoImpl@361ee3df
com.mycompany.understanding.spring.MyServiceImpl@2602613b
Performing tasks .............
printing data
com.mycompany.understanding.spring.MyDaoImpl@663d7bfb


3. When Service bean is singleton and Dao bean is prototype

com.mycompany.understanding.spring.MyServiceImpl@7188eb7
Performing tasks .............
printing data
com.mycompany.understanding.spring.MyDaoImpl@5d419404
com.mycompany.understanding.spring.MyServiceImpl@7188eb7
Performing tasks .............
printing data
com.mycompany.understanding.spring.MyDaoImpl@5d419404
com.mycompany.understanding.spring.MyServiceImpl@7188eb7
Performing tasks .............
printing data
com.mycompany.understanding.spring.MyDaoImpl@5d419404


You can only see 1 instance of service bean and 1 instance of prototype bean. This is not desired as in some scenarios you want to create new prototype bean again and again. This is where lookup-method comes in handy.

4. When Service bean is prototype and Dao bean is singleton.

com.mycompany.understanding.spring.MyServiceImpl@5d419404
Performing tasks .............
printing data
com.mycompany.understanding.spring.MyDaoImpl@7c5cc270
com.mycompany.understanding.spring.MyServiceImpl@528f1577
Performing tasks .............
printing data
com.mycompany.understanding.spring.MyDaoImpl@7c5cc270
com.mycompany.understanding.spring.MyServiceImpl@2fca61f9
Performing tasks .............
printing data
com.mycompany.understanding.spring.MyDaoImpl@7c5cc270


You can see 3 instances of the service beans and only 1 instance of the dao bean. Simple examples like this can clarify the concepts.

Scenario 3 is not desired as in some scenarios, and you want to create new prototype bean again and again. This is where lookup-method comes in handy. I will cover this in the next post.

Labels: ,

Feb 13, 2014

Understanding Spring scopes -- Singleton Vs Prototype

Spring Interview Questions and Answers Q1 - Q14 are FAQs

Q1 - Q4 Overview & DIP Q5 - Q8 DI & IoC Q9 - Q10 Bean Scopes Q11 Packages Q12 Principle OCP Q14 AOP and interceptors
Q15 - Q16 Hibernate & Transaction Manager Q17 - Q20 Hibernate & JNDI Q21 - Q22 read properties Q23 - Q24 JMS & JNDI Q25 JDBC Q26 Spring MVC Q27 - Spring MVC Resolvers

You will be hard pressed to find a Java project that does not use Spring, hence it pays to know its fundamentals. These questions and answers on Spring scopes are often asked in good job interviews.

Q. Does Spring dependency injection happen during compile time or runtime?
A. Runtime during creating an object.

Q9. What is the difference between prototype scope and singleton scope? Which one is the default?
A9. Singleton means single bean instance per IoC container, and prototype means any number of object instances per IoC container. The default scope is "singleton".

Q. When will you use singleton scope? When will you use prototype scope?
A. Singleton scope is used for stateless object use. For example, injectiong a DAO (i.e. Data Access Object) into a service object. DAOs don't need to maintain conversation state. For example,


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="myDaoDef" class="com.mycompany.understanding.spring.MyDaoImpl" scope="singleton"/>
    
    <bean id="myServiceDef" class="com.mycompany.understanding.spring.MyServiceImpl" scope="singleton"> 
       <constructor-arg name="myDao" ref="myDaoDef" /> 
    </bean>

</beans>


Prototype is useful when your objects maintain state in a multi-threaded environment. Each thread needs to use its own object and cannot share the single object. For example, you might hava a RESTFul web service client making multi-threaded calls to Web services. The REST easy client APIs like RESTEasy uses the Apache Connection manager which is not thread safe and each thread should use its own client. Hence, you need to use the prototype scope.

Q. Would both singleton and prototype bean's life cycle be managed by the Spring IoC container?
A. Yes and no. The singleton bean's complete life cycle will be managed by Spring IoC container, but with regards to prototype scope, IoC container only partially manages the life cycle - instantiates, configures, decorates and otherwise assembles a prototype object, hands it to the client and then has no further knowledge of that prototype instance. As per the spring documentation

"This means that while initialization lifecycle callback methods will be called on all objects regardless of scope, in the case of prototypes, any configured destruction lifecycle callbacks will not be called. It is the responsibility of the client code to clean up prototype scoped objects and release any expensive resources that the prototype bean(s) are holding onto."

Q. What happens if you inject a prototype scoped bean into a singleton scoped bean?
A. A new prototype scoped bean will be injected into a singleton scoped bean once at runtime, and the same prototype bean will be used by the singleton bean.

Q. What if you want the singleton scoped bean to be able to acquire a brand new instance of the prototype-scoped bean again and again at runtime?
A. In this  use-case, there is no use in just dependency injecting a prototype-scoped bean into your singleton bean, because as stated above, this only happens once when the Spring container is instantiating the singleton bean and resolving and injecting its dependencies. You can just inject a singleton (e.g. a factory) bean and then use Java class to instantiate (e.g with a newInstance(...) or create(..) method) a new bean again and again at runtime without relying on Spring or alternatively have a look at Spring's "method injection". As per Spring documentation for "Lookup method injection"




"Lookup method injection refers to the ability of the container to override methods on container managed beans, to return the result of looking up another named bean in the container. The lookup will typically be of a prototype bean as in the scenario described above. The Spring Framework implements this method injection by dynamically generating a subclass overriding the method, using bytecode generation via the CGLIB library."


Q10. What are the scopes defined in HTTP context?
A10. Following scopes are only valid in the context of a web-aware Spring ApplicationContext.

  • request Scope is for a single bean definition to the lifecycle of a single HTTP request.In other words each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. 
  • session Scope is for a single bean definition to the lifecycle of a HTTP Session. 
  • global session Scope is for a  single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. 

Q. Does Spring allow you to define your own bean scopes?
A. Yes, from Spring 2.0 onwards you can define custom scopes. For example,
  • You can define a ThreadOrRequest and ThreadOrSession scopes to be able to switch between the environment you run in like JUnit for testing and Servlet container for running as a Web application. 
  • You can write a custom scope to inject stateful objects into singleton services or factories.
  • You can write a custom bean scope that would create new instances per each JMS message consumed
  • Oracle Coherence has implemented a datagrid scope for Spring beans. You will find many others like this.


In the next post, I will demonstrate "singleton" and prototype scopes with tutorial like code, Stay tuned.

Relevant tutorials:

Labels: ,

Feb 11, 2014

Dynamically generating "insert" SQL statments

There are times where you need to generate "INSERT" SQL statements from existing data. For example, you may have a production release ready "Delete" SQL statement as shown below to remove some existing records.


Delete from employee_table WHERE first_name like ('P%')

For this script, you need to have a rollback script. It can be dynamically generated as shown below.

SELECT 'INSERT INTO employee_table ( first_name, surname, birth_date, created_date, updated_by) VALUES (' 
|| '''' || first_name || ''' '
|| ',''' || surname || ''' '
|| ',''' || convert(CHAR(20),birth_date) || ''' '
|| ',''' || convert(CHAR(20),created_date) || ''' '
|| ',''' || updated_by || ''' '
FROM employee_table  WHERE first_name like ('P%')


Alternatively, there are database management tools like TOAD, DBArtisan, SQL Developer, etc that allows you to generate SQL statements from the selected records. At times those generated insert statements need to be massaged like removing the auto generated primary key ids, timestamp,  etc. You can make the changes in Notepad++ Find/Replace with regular expression feature. For example, the following generated insert statement


INSERT INTO employee_table (emp_id, first_name, surname, birth_date, created_date, updated_by, timestamp)
   VALUES ( 1365, 'Peter', 'Smith', '03 Dec 1950', '03 Jun 2013 11:15:59.456 AM', 'user1', 0x0000090209F4A6E6)

can be modified with the following regular expressions

For:   emp_id

Find: \(\s* emp_id,
Replace with: (

Find: VALUES\s*\(\s*\d+,
Replace with: VALUES (


For:  timestamp

Find: ,timestamp
Replace with:


Find:0x[0-9A-G]+,
Replace with:

Labels:

Feb 4, 2014

Transaction management in SQL -- Sybase example




You may also like:

Q. How do you perform transaction management in SQL stored procedures?
A. Handled with begin, commit, and rollback 'tran' commands in Sybase server.

Q. Why is it important?
A. It is important to leave the database in a consistent state.

Q. Can you give an example?
A. For example, as demonstrated below, if you are going to delete 21 records from a database table, you can use transaction management to ensure that a GIVEN COUNT say 21 records are either deleted or rolled back. Partially deleting records can leave the database  in inconsistent state.


print 'Before delete from employee_table'
print '-------------------------------'

DECLARE  @EMPLOYEE_IN_CLAUSE  varCHAR(10000)
Select @EMPLOYEE_IN_CLAUSE = "'John', 'Joseph'"

exec ('select * from semployee_table where first_name in (' +  @EMPLOYEE_IN_CLAUSE +  '))
exec ('select count(*) as deleted_transact_records_count from employee_table where first_name in (' +  @EMPLOYEE_IN_CLAUSE + ') )

declare @rowcount int
select  @rowcount = 0

--transaction starts
begin tran

--Deletion
print 'delete some records from employee_table'
exec ('delete from sd_wrap..employee_table where first_name in (' +  @EMPLOYEE_IN_CLAUSE + ') and bean_name = ''TransactDetail''')

--number of rows deleted
select @rowcount = @rowcount + @@rowcount

--commit or rollback
if @rowcount = 21
begin
   commit tran
   print 'success'
end
else
begin
   rollback tran
   print 'failed'
end


print 'After delete from employee_table'
print '-------------------------------'

exec ('select * from employee_table where first_name in (' +  @EMPLOYEE_IN_CLAUSE +  '))
exec ('select count(*) as deleted_transact_records_count from sd_wrap..employee_table where first_name in (' +  @EMPLOYEE_IN_CLAUSE + ') )

go


In Sybase, @@rowcount variable returns the number of rows affected by the query. This post also demonstrates a production ready script with proper print statements, transaction management, etc to perform a basic DELETE operation. Same thing is true for insert and update operations.

Q. Do you require any other script if the above deletion causes unexpected  issue?
A. Yes, you need a rollback script with 21 insert statements to revert the changes. In other words script to put the deleted data back.

Q. Is there a smarter way to generate the insert script or will you type them in one by one?
A. There is a smarter way using a select statement to generate all the 21 insert statements with the following query.

SELECT 'INSERT INTO employee_table ( first_name, surname, salary) VALUES (' 
|| '''' || fist_name || ''' '
|| ',''' || surname || ''' '
|| ',''' || salary 

|| ')'

FROM employee_table 
WHERE first_name in ('John', 'Joseph');

Another SQL generation tip with Excel spreadsheet.

You may also like:

Labels: ,