java architect questions

Upload: aryabasu1

Post on 04-Apr-2018

231 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/30/2019 Java Architect Questions

    1/22

    Java Interview Questions and Answers on Software ArchitectureGood caliber candidates have the ability to look

    at the big picture and drill down into details.The line between software development and

    software architecture is a tricky one. Regardless

    of you are an architect, developer, or both, oneneeds to have a good understanding of the

    overall software architecture. The following

    Java interview questions are very popular withthe interviewers and it can significantly

    influence the decision of Hire/No Hire. So, it

    really pays to have a good overview of various

    possible architectures. The questions shownbelow will also make a good platform for

    further questions depending on your answers.

    Be prepared for a white board session on

    architectures, especially the bird's eye view of

    the last application you had worked on. Therewill be lots of follow on questions like why a

    particular approach was used?, what are the

    benefits and drawbacks of a particularapproach?, etc.

    Q. Can you draw me a 1000 foot view of the architecture of the system you were/areinvolved in, in your current/last position?Q. Can you describe the architecture of a medium-to-large scale system that youactually designed or implemented?Q. Can you white board the components of the system you recently worked on?Q. How would you go about designing a JEE shopping cart application?Q. Can you discuss some of the high level architectures you are experienced with?

    A. There are a number of high level conceptual architectures as discussed below. These individual

    architectures can be mixed and matched to produce hybrid architectures.

    Model-View-Controller Architecture

    Most web and stand-alone GUI applications follow this pattern. For example, Struts and Spring MVC

    frameworks and Swing GUI.

  • 7/30/2019 Java Architect Questions

    2/22

    The model represents the core business logic and state. The view renders the content of the model

    state by adding display logic. The controller translates the interaction with the view into action to be

    performed by the model. The actions performed by a model include executing the business logic

    and changing the state of the model. Based on the user interactions, the controller selects an

    appropriate view to render. The controller decouples the model from the view.

    Service Oriented Architecture (SOA)

    The business logic and application state are exposed as reusable services. An Enterprise Service

    Bus (ESB) is used as an orchestration and mediation layer to decouple the applications from the

    services.

    http://3.bp.blogspot.com/-5xMabjujz90/TpfWzR8riUI/AAAAAAAAAHo/Q_6AbHukNc0/s1600/architecture-mvc.JPG
  • 7/30/2019 Java Architect Questions

    3/22

    The above architecture has 5 tiers. The application tier could be using a typical MVC architecture.

    The service orchestration tier could be using ESB products like Oracle Service Bus, TIBCO, etc and

    BPM products like Lombardi BPM, Pega BPM, etc. In the above diagram, the ESB integrates with

    the BPM via messaging queues. The service tier consists of individual services that can be

    accessed through SOAP or RESTful web services. The SOA implementation requires change

    agents to drive adoption of new approaches. The BPM, application integration, and real-time

    information all contribute to dynamically changing how business users do their jobs. So, it needs full

    support from the business, requiring restructuring and also it can take some time to realize the

    benefits of SOA. Cloud computing is at the leading edge of its hype and as a concept compliments

    SOA as an architectural style. Cloud computing is expected to provide a computing capability that

    can scale up (to massive proportions) or scale down dynamically based on demand. This implies a

    very large pool of computing resources either be within the enterprise intranet or on the Internet (i.e

    on the cloud).

    User Interface (UI) Component Architecture

    This architecture is driven by a user interface that is made up of a number of discrete components.

    Each component calls a service that encapsulates business logic and hides lower level details.

    Components can be combined to form new composite components allowing richer functionality.

    http://4.bp.blogspot.com/-itE-vaYFq2k/TpfXA7pjE5I/AAAAAAAAAHw/WyVIDkSSOcg/s1600/architecture-SOA.JPG
  • 7/30/2019 Java Architect Questions

    4/22

    These components can also be shared across a number of applications. For example, JavaScript

    widgets, Java Server Faces (JSF) components, etc.

    RESTful data composition Architecture

    The user interface can be built by calling a number of underlying services that are each responsible

    for building part of a page. The user interface translates and combine the data in different formatslike XML(translate to HTML using XSLT), JSON (Java Script Object Notation), ATOM (feed for mail

    messages and calendar applications), RSS (for generating RSS feeds), etc.

    HTML composition Architecture

    http://2.bp.blogspot.com/-ZpQcdSyIHms/TpfXkxcILNI/AAAAAAAAAIA/dkiTkzctO3I/s1600/architecture-restful-composition.JPGhttp://2.bp.blogspot.com/-wwsi-ruhXBw/TpfXUXZoOxI/AAAAAAAAAH4/bP1crmprDp4/s1600/architecture-ui-component.JPGhttp://2.bp.blogspot.com/-ZpQcdSyIHms/TpfXkxcILNI/AAAAAAAAAIA/dkiTkzctO3I/s1600/architecture-restful-composition.JPGhttp://2.bp.blogspot.com/-wwsi-ruhXBw/TpfXUXZoOxI/AAAAAAAAAH4/bP1crmprDp4/s1600/architecture-ui-component.JPG
  • 7/30/2019 Java Architect Questions

    5/22

    In this architecture, multiple applications output fragments of HTML that are combined to generate

    the final user interface. For example, Java portlets used inside a portal application server to

    aggregate individual content..

    Plug-in Architecture

    In this architecture, a core application defines an interface, and the functionality will be implemented

    as a set of plug-ins that conform to that interface. For example, the the Eclipse RCP framework,

    Maven build tool, etc use this architecture.

    Event Driven Architecture (EDA)

    http://3.bp.blogspot.com/-qVn3pyioemM/TpfYKnHavzI/AAAAAAAAAIQ/nRlm0tf8Izc/s1600/architecture-plugin.JPGhttp://1.bp.blogspot.com/-qNfK1SFf40s/TpfX-B6pikI/AAAAAAAAAII/y4zZDYixHfs/s1600/architecture-html-composition.JPGhttp://3.bp.blogspot.com/-qVn3pyioemM/TpfYKnHavzI/AAAAAAAAAIQ/nRlm0tf8Izc/s1600/architecture-plugin.JPGhttp://1.bp.blogspot.com/-qNfK1SFf40s/TpfX-B6pikI/AAAAAAAAAII/y4zZDYixHfs/s1600/architecture-html-composition.JPG
  • 7/30/2019 Java Architect Questions

    6/22

    The EDA pattern decouples the interactions between the event publishers and the event consumers.

    Many to many communications are achieved via a topic, where one specific event can be consumed

    by many subscribers. The EDA also supports asynchronous operations and acknowledgments

    through event messaging. This architecture requires effective monitoring in place to track queue

    depth, exceptions, and other possible problems. The traceability, isolation, and debugging of an

    event can be difficult in some cases. This architecture is useful in scenarios where the business

    process is inherently asynchronous, multiple consumers are interested in an event(e.g. order statushas changed to partially-filled ), no immediate acknowledgment is required (e.g. an email is sent with

    the booking details and itinerary), and real-time request/response is not required (e.g. a long running

    report can be generated asynchronously and made available later via online or via email).

    Most conceptual architectures use a hybrid approach using a combination of different architectures

    based on the benefits of each approach and its pertinence to your situation. Here is a

    sample hybrid approach depicting an online trading system.

    http://2.bp.blogspot.com/-03TVBd4PM-M/TpfYSJcpG7I/AAAAAAAAAIY/NhRDAd9LFVw/s1600/architecture-event-driven.JPG
  • 7/30/2019 Java Architect Questions

    7/22

  • 7/30/2019 Java Architect Questions

    8/22

    Q. What are the different application integration styles?

    A. There are a number of different integration styles like

    1. Shared database

    2. batch file transfer3. Invoking remote procedures (RPC)

    4. Exchanging asynchronous messages over a message oriented middle-ware (MOM).

    http://1.bp.blogspot.com/-PzRrLNGPU9U/TzSyk9vzpYI/AAAAAAAAASk/wsDCrNTg9FM/s1600/integration-styles.JPG
  • 7/30/2019 Java Architect Questions

    9/22

    Q. What are the different styles of Web Services used for application integration?

    A. SOAP WS and RESTful Web Service

    Q. What are the differences between both SOAP WS and RESTful WS?

    A.

    The SOAP WS supports both remote procedure call (i.e. RPC) and message oriented

    middle-ware (MOM) integration styles. The Restful Web Service supports only RPC integration

    style.

    The SOAP WS is transport protocol neutral. Supports multiple protocols like HTTP(S),

    Messaging, TCP, UDP SMTP, etc. The REST is transport protocol specific. Supports only HTTP

    or HTTPS protocols.

    The SOAP WS permits only XML data format.You define operations, which tunnels

    through the POST. Thefocus is on accessing the named operations and exposing theapplication logic as a service. The REST permits multiple data formats like XML, JSON data,

    text, HTML, etc. Any browser can be used because the REST approach uses the standard

    GET, PUT, POST, and DELETE Web operations. The focus is on accessing the named

    resources and exposing the data as a service. REST has AJAX support. It can use the

    XMLHttpRequest object. Good for stateless CRUD (Create, Read, Update, and Delete)

    operations.

    GET - represent()POST - acceptRepresention()PUT - storeRepresention()DELETE - removeRepresention()

    SOAP based reads cannot be cached. REST based reads can be cached. Performs and

    scales better.

    SOAP WS supports both SSL security and WS-security, which adds some enterprise

    security features like maintaining security right up to the point where it is needed, maintaining

    identities through intermediaries and not just point to point SSL only, securing different parts of

    the message with different security algorithms, etc. The REST supports only point-to-point SSL

    security. The SSL encrypts the whole message, whether all of it is sensitive or not.

    The SOAP has comprehensive support for both ACID based transaction management

    for short-lived transactions and compensation based transaction management for long-running

    transactions. It also supports two-phase commit across distributed resources. The RESTsupports transactions, but it is neither ACID compliant nor can provide two phase commit

    across distributed transactional resources as it is limited by its HTTP protocol.

    The SOAP has success or retry logic built in and provides end-to-end reliability even

    through SOAP intermediaries. REST does not have a standard messaging system, and expects

    clients invoking the service to deal with communication failures by retrying.

  • 7/30/2019 Java Architect Questions

    10/22

    Q.How would you decide what style of Web Service to use? SOAP WS or REST? A. In general, a REST based Web service is preferred due to its simplicity, performance,scalability, and support for multiple data formats. SOAP is favored where service requires

    comprehensive support for security and transactional reliability.

    The answer really depends on the functional and non-functional requirements. Asking thequestions listed below will help you choose.

    Does the service expose data or business logic? (REST is a better choice for

    exposing data, SOAP WS might be a better choice for logic).Do the consumers and the service

    providers require a formal contract? (SOAP has a formal contract via WSDL)

    Do we need to support multiple data formats?

    Do we need to make AJAX calls? (REST can use the XMLHttpRequest)

    Is the call synchronous or asynchronous?

    Is the call stateful or stateless? (REST is suited for statless CRUD operations)

    What level of security is required? (SOAP WS has better support for security)

    What level of transaction support is required? (SOAP WS has better support for

    transaction management)

    Do we have limited band width? (SOAP is more verbose)

    Whats best for the developers who will build clients for the service? (REST is

    easier to implement, test, and maintain)

    Q.What tools do you use to test your Web Services?A.SoapUItool for SOAP WS and the Firefox "poster" plugin for RESTFul services.

    Q.What is the difference between SOA and a Web service?A.

    SOA isa software design principle and an architectural pattern for implementing looselycoupled, reusable and coarse grained services. You can implement SOA using any protocolssuch as HTTP, HTTPS, JMS, SMTP, RMI, IIOP (i.e. EJB uses IIOP), RPC etc. Messages canbe in XML or Data Transfer Objects (DTOs).

    Web service isan implementation technology and one of the ways to implement SOA. You canbuild SOA based applications without using Web services for example by using othertraditional technologies like Java RMI, EJB, JMS based messaging, etc. But what Web servicesoffer is the standards based and platform-independent service via HTTP, XML, SOAP, WSDLand UDDI, thus allowing interoperability between heterogeneous technologies such as J2EEand .NET.

  • 7/30/2019 Java Architect Questions

    11/22

    Q.Web services when you can use traditional style middle-ware such as RPC, CORBA, RMIand DCOM?A.

    Thetraditional middle-warestightly couple connections to the applications and it can break if

    you make any modification to your application. Tightly coupled applications are hard to maintainand less reusable. Generally do not support heterogeneity. Do not work across Internet. Can bemore expensive and hard to use.

    Web Servicessupport loosely coupled connections. The interface of the Web service providesa layer of abstraction between theclientand the server. The loosely coupled applicationsreduce the cost of maintenance and increases re-usability. Web Services present a new form ofmiddle-ware based on XML and Web. Web services are language and platform independent.You can develop a Web service using any language and deploy it on to any platform, from smalldevice to the largest supercomputer. Web service uses language neutral protocols such asHTTP and communicates between disparate applications by passing XML messages to eachother via a Web API. Do work across internet, less expensive and easier to use.

    Q.What are the different approaches to developing a SOAP based Web service?A.2approaches.

    The contract-first approach, where you define the contract first with XSD and WSDL

    and the generate the Java classes from the contract.

    The contract-last approach where you define the Java classes first and then generate

    the contract, which is the WSDL file from the Java classes.

    Note:The WSDL describes all operations that the service provides, locations of the endpoints(i.e.e where the services can be invoked), and simple and complex elements that can bepassed in requests and responses.

    Q.What are the pros and cons of each approach, and which approach would you prefer?

    A.

    Contract-first Web service

    PROS:

    Clients are decoupled from the server, hence the implementation logic can be revised on

    the server without affecting the clients.

    Developers can work simultaneously on client and server side based on the contract

    both agreed on.

  • 7/30/2019 Java Architect Questions

    12/22

    You have full control over how the request and response messages are constructed --

    for example, should "status" go as an element or as an attribute? The contract clearly defines it.

    You can change OXM (i.e. Object to XML Mapping) libraries without having to worry if the

    "status" would be generated as "attribute" instead of an element. Potentially, even Web service

    frameworks and tool kits can be changed as well from say Apache Axis to Apache CXF, etc

    CONS:

    More upfront work is involved in setting up the XSDs and WSDLs. There are tools like

    XML Spy, Oxygen XML, etc to make things easier. The object models need to be written as

    well.

    Developers need to learn XSDs and WSDLs in addition to just knowing Java.

    Contract-last Web service

    PROS:

    Developers don't have to learn anything related to XSDs, WSDLs, and SOAP. The

    services are created quickly by exposing the existing service logic with frameworks/tool sets.

    For example, via IDE based wizards, etc.

    The learning curve and development time can be smaller compared to the Contract-first

    Web service.

    CONS:

    The development time can be shorter to initially develop it, but what about the on going

    maintenance and extension time if the contract changes or new elements need to be added? In

    this approach, since the clients and servers are more tightly coupled, the future changes may

    break the client contract and affect all clients or require the services to be properly versioned

    and managed.

    In this approach, The XML payloads cannot be controlled. This means changing your

    OXM libraries could cause something that used to be an element to become an attribute with

    the change of the OXM.

    So, which approach will you choose?

    The best practice is to use "contract-first", and here is the link that explains this much better

    with examples --> contract-first versus contract-last web servicesIn a nutshell, the contract-last

    is more fragile than the "contract-first". You will have to decide what is most appropriate based

    on your requirements, tool sets you use, etc.

    http://static.springsource.org/spring-ws/site/reference/pdf/spring-ws-reference.pdfhttp://static.springsource.org/spring-ws/site/reference/pdf/spring-ws-reference.pdfhttp://static.springsource.org/spring-ws/site/reference/pdf/spring-ws-reference.pdf
  • 7/30/2019 Java Architect Questions

    13/22

    sfssfsdfdsf

    Note: More Java Web Services interview questions and answers including WSDL, SOAP,

    UDDI, JAXR, SAAJ, etc are covered in Java/J2EE Job Interview Companion with diagrams.

    Spring Interview Questions and Answers: Overview

    Q.What do you understand by the terms Dependency Inversion Principle (DIP), Dependency Injection (DI) and

    Inversion of Control (IoC) container ?

    A.

    Dependency Inversion Principle (DIP) is a design principle which is insome ways related to the Dependency Injection (DI) pattern. The idea of DIP is that higher layers of your application

    should not directly depend on lower layers. Dependency Inversion Principle does not imply Dependency Injection.

    This principle doesnt say anything about how higher la yers know what lower layer to use. This could be done as

    shown below by coding to interface using a factory pattern or through Dependency Injection by using an IoC

    container like Spring framework, Pico container, Guice, or Apache HiveMind.

    http://4.bp.blogspot.com/-oQAjSRPGpJk/TpKVo_7jdLI/AAAAAAAAAG4/-7yk7WoxIzg/s1600/DIP-oo-principle.JPG
  • 7/30/2019 Java Architect Questions

    14/22

    The Dependency Inversion Principle (DIP) states that

    High level modules should not depend upon low level modules. Both should depend upon abstractions.

    Abstractions should not depend upon details. Details should depend upon abstractions.

    When this principle is applied, the higher level classes will not be working directly with the lower level classes, butwith an abstract layer. This gives us the flexibility at the cost of increased effort.Here are some code snippets for DIP.

    Firstly define the abstraction layer.

    ?

    1

    2

    3

    45

    package principle_dip2;

    publicinterfaceAnimalHandler {publicabstractvoidhandle( );

    }

    ?1

    2

    34

    5

    package principle_dip2;

    publicinterfaceAnimalHelper {publicabstractvoidhelp( );

    }

    Now the implementation that depends on the abstraction as opposed to the implementation.

    ?

    1

    2

    34

    5

    67

    8

    910

    11

    12

    13

    1415

    package principle_dip2;

    publicclassCircusService {

    AnimalHandler handler;

    publicvoidsetHandler(AnimalHandler handler) {this.handler = handler;

    }

    publicvoidshowStarts( ) {//code omitted for brevityhandler.handle( );

    }

    }

    ?

    1

    2

    3

    package principle_dip2;

    publicclassTigerHandler implements AnimalHandler{

    http://java-success.blogspot.com/2011/10/spring-interview-questions-and-answers.htmlhttp://java-success.blogspot.com/2011/10/spring-interview-questions-and-answers.htmlhttp://java-success.blogspot.com/2011/10/spring-interview-questions-and-answers.htmlhttp://java-success.blogspot.com/2011/10/spring-interview-questions-and-answers.htmlhttp://java-success.blogspot.com/2011/10/spring-interview-questions-and-answers.htmlhttp://java-success.blogspot.com/2011/10/spring-interview-questions-and-answers.htmlhttp://java-success.blogspot.com/2011/10/spring-interview-questions-and-answers.htmlhttp://java-success.blogspot.com/2011/10/spring-interview-questions-and-answers.htmlhttp://java-success.blogspot.com/2011/10/spring-interview-questions-and-answers.htmlhttp://java-success.blogspot.com/2011/10/spring-interview-questions-and-answers.htmlhttp://java-success.blogspot.com/2011/10/spring-interview-questions-and-answers.htmlhttp://java-success.blogspot.com/2011/10/spring-interview-questions-and-answers.html
  • 7/30/2019 Java Architect Questions

    15/22

    4

    56

    7

    8

    910

    11

    1213

    14

    1516

    AnimalHelper helper;

    publicvoidsetHelper(AnimalHelper helper) {this.helper = helper;

    }

    publicvoidhandle( ){//...helper.help( );//...

    }}

    ?

    1

    23

    45

    6

    78

    package principle_dip2;

    publicclassTigerHelper implements AnimalHelper{

    publicvoidhelp( ){//......

    }}

    Dependency Injection (DI) is a pattern of injecting a classs dependencies into it atruntime. This is achieved by defining the dependencies as interfaces, and then injecting in a concrete class

    implementing that interface to the constructor. This allows you to swap in different implementations without having to

    modify the main class. The Dependency Injection pattern also promotes high cohesion by promoting the Single

    Responsibility Principle (SRP), since your dependencies are individual objects which perform discrete specialized

    tasks like data access (via DAOs) and business services (via Service and Delegate classes) .

    The Inversion of Control Container (IoC) is a container that supportsDependency Injection. In this you use a central container like Spring framework, Guice, or HiveMind, which defines

    what concrete classes should be used for what dependencies throughout your application. This brings in an added

    flexibility through looser coupling, and it makes it much easier to change what dependencies are used on the fly. The

    basic concept of the Inversion of Control pattern is that you do not create your objects but describe how they should

    be created. You don't directly connect your components and services together in code but describe which services

    are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC

    container) is then responsible for hooking it all up. Applying IoC, objects are given their dependencies at creation time

    by some external entity that coordinates each object in the system. That is, dependencies are injected into objects.

    So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.

    The real power ofDIandIoCis realized in its ability to replace the compile time binding of the relationships betweenclasses with binding those relationships at runtime. For example, in Seam framework, you can have a real and mockimplementation of an interface, and at runtime decide which one to use based on a property, presence of another file,or some precedence values. This is incredibly useful if you think you may need to modify the way your application

    http://java-success.blogspot.com/2011/10/spring-interview-questions-and-answers.htmlhttp://java-success.blogspot.com/2011/10/spring-interview-questions-and-answers.htmlhttp://java-success.blogspot.com/2011/10/spring-interview-questions-and-answers.html
  • 7/30/2019 Java Architect Questions

    16/22

    behaves in different scenarios. Another real benefit of DI and IoC is that it makes your code easier to unit test. Thereare other benefits like promoting looser coupling without any proliferation of factory and singleton design patterns,follows a consistent approach for lesser experienced developers to follow, etc. These benefits can come in at the costof the added complexity to your application and has to be carefully manged by using them only at the right placeswhere the real benefits are realized, and not just using them because many others are using them.

    Note:The CDI (Contexts and Dependency Injection) is an attempt at describing a true standard on Dependency

    Injection. CDI is a part of the Java EE 6 stack, meaning an application running in a Java EE 6 compatible containercan leverage CDI out-of-the-box. Weld is the reference implementation of CDI.

    --> Q.In your experience, why would you use Spring framework?A.

    Spring has a layered architecture with over 20 modules to choose from. This means, use what you need and

    leave what you don't need now. Spring simplifies JEE through POJO programming. There is no behind the scene

    magic in Spring as in JEE programming. POJO programming enables continuous integration and testability.

    Spring framework's core functionality is dependency injection (DI). Dependency injection promotes easy unit

    testing and more maintainable and flexible code. DI code is much easier to test. The functionality expressed by the

    object can be tested in a black box by building 'mock' objects implementing the interfaces expected by your

    http://3.bp.blogspot.com/-BnOnrKC5_cE/TpKT-yR7n4I/AAAAAAAAAG0/CCDYfpq3B5Y/s1600/spring-overview.JPG
  • 7/30/2019 Java Architect Questions

    17/22

    application logic. DI code is much easier to reuse as the 'depended' functionality is extrapolated into well defined

    interfaces, allowing separate objects whose configuration is handled by a suitable application platform to be plugged

    into other objects at will. DI code is more flexible. It is innately loosely coupled code to an extreme. This allows the

    programmer to pick and choose how objects are connected based exclusively on their required interfaces on one end

    and their expressed interfaces on the other.

    Spring supports Aspect Oriented Programming (AOP), which enables cohesive development by separating

    application business logic from system services. Supporting functionalities like auditing, gathering performanceandmemory metrics, etc can be enabled through AOP.

    Spring also provides a lot of templates which act as base classes to make using the JEE standardtechnologies a breeze to work with. For example, the JdbcTemplate works well with JDBC, the JpaTemplate does

    good things with JPA, JmsTemplate makes JMS pretty straightforward. The RestTemplate is simply awesome in it's

    simplicity. Simplicity means more readable and maintainable code.

    When writing software these days, it is important to try and decouple as much middleware code from your

    business logic as possible. The best approach when using remoting is to use Spring Remoting which can then use

    any messaging or remoting technology under the covers. Apache Camel is a powerful open source integration

    framework based on known Enterprise Integration Patterns with powerful Bean Integration. Apache Camel is

    designed to work nicely with the Spring Framework in a number of ways.

    It also provides declarative transactions, job scheduling, authentication, a fully-fledged MVC web

    framework, and integration to other frameworkslike Hibernate, iBatis, JasperReports, JSF, Struts,Tapestry, Seam, Quartz job scheduler, etc.

    Spring beans can be shared between different JVMs using Terracotta. This allows you to take existing

    beans and spread them across a cluster, turn Spring application context events into distributed events, export

    clustered beans via Spring JMX, and make your Spring applications highly available and clustered. Spring also

    integrate well with other clustering solutions like Oracle's Coherance.

    Spring favors unchecked exceptions and eliminates unsightly try, catch, and finally (and some timestry/catch within finally itself) blocks. The Spring templates like JpaTemplate takes care of closing or releasing a

    database connection. This prevents any potential resource leaks and promotes more readable code.

    It prevents the proliferation of factory and singleton pattern classes that need to be created to promote loose

    coupling if not for using a DI framework like Spring or Guice.

    Q.In your experience, what do you don't like about Spring? Are there any pitfalls?

    A.

    Spring has become very huge and bulky. So, don't over do it by using all its features because of the hype

    that Spring is good. Look at what parts of Spring really provides some benefits for your project and use those parts. In

    most cases, it is much better to use proven frameworks like Spring than create your own equivalent solution from a

    maintenance and applying the best practices perspective. For example, all spring templates (jdbc, rest, jpa etc.) have

    the following advantages -- perform common setup routines for you, let you skip the boilerplate and concentrate on

    the logic you want.

    Spring MVC is probably not the best Web framework. There are other alternatives like Struts 2, Wicket, and

    JSF. Having said this, Spring integrates well with the other Web frameworks like Struts, JSF, etc.

    The XML files can get bloated. This can be minimized by carefully considering other options like

    annotations, JavaConfig, and having separate XML configuration files.

    Q.What are the different types of IoC (dependency injection) ?A.There are three types of dependency injection:

    Constructor Injection (e.g. Spring): Dependencies are provided as constructor parameters.

    Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter

    methods).

    Interface Injection (e.g. Avalon): Injection is done through an interface.

  • 7/30/2019 Java Architect Questions

    18/22

    Q.Have you used any other Dependency Injection (DI) frameworks?

    A. Yes, Guice, Hivemind, and Seam.

  • 7/30/2019 Java Architect Questions

    19/22

    Hibernate Interview Questions and Answers: Overview

    Q. How will you configure Hibernate?

    A. The configuration files hibernate.cfg.xml (or hibernate.properties) and mapping files *.hbm.xml are used by the

    Configuration class to create (i.e. configure and bootstrap hibernate) the SessionFactory, which in turn creates the

    Session instances. Session instances are the primary interface for the persistence service.

    hibernate.cfg.xml (alternatively can use hibernate.properties): These two files are used to configure the

    hibernate sevice (connection driver class, connection URL, connection username, connection password, dialect etc).

    If both files are present in the classpath then hibernate.cfg.xml file overrides the settings found in the

    hibernate.properties file.

    Mapping files (*.hbm.xml): These files are used to map persistent objects to a relational database. It is the best

    practice to store each object in an individual mapping file (i.e mapping file per class) because storing large number of

    persistent classes into one mapping file can be difficult to manage and maintain. The naming convention is to use the

    same name as the persistent (POJO) class name. For example Account.class will have a mapping file named

    Account.hbm.xml. Alternatively, hibernate annotations can be used as part of your persistent class code instead of

    the *.hbm.xml files.

    Q.What is a SessionFactory? Is it a thread-safe object?A.SessionFactoryis Hibernate's concept of a single datastore and isthreadsafeso that many threads can access itconcurrently and request for sessions and immutable cache of compiled mappings for a single database. ASessionFactory is usually only built once at startup. SessionFactory should be wrapped in some kind of singleton sothat it can be easily accessed in an application code.

    SessionFactory sessionFactory = new Configuration( ).configure( ).buildSessionfactory( );

    Q.What is a Session? Can you share a session object between different threads? A. Session is a light weight and a non-threadsafe object (No, you cannot share it between threads) that represents asingle unit-of-work with the database. Sessions are opened by a SessionFactory and then are closed when all work iscomplete. Session is the primary interface for the persistence service. A session obtains a database connection lazily(i.e. only when required). To avoid creating too many sessions ThreadLocal class can be used as shown below to get

    http://4.bp.blogspot.com/-UtRt8DaB_ZI/ToEUo9wUtRI/AAAAAAAAAEs/fN1VqMhQJks/s1600/hibernate_overview.JPG
  • 7/30/2019 Java Architect Questions

    20/22

    the current session no matter how many times you make call to the currentSession( ) method.

    ?

    1

    2

    3

    45

    67

    8

    9

    1011

    12

    13

    14

    publicclassHibernateUtil {

    publicstaticfinal ThreadLocal local = newThreadLocal();

    publicstaticSession currentSession() throws HibernateException {Session session = (Session) local.get();//open a new session if this thread has no sessionif(session == null) {

    session = sessionFactory.openSession();local.set(session);

    }returnsession;

    }}

    It is also vital that you close your session after your unit of work completes. Note: Keep your Hibernate Session API

    handy. Quite often, hibernate is used with Spring framework, using the HibernateTemplate.

    -->Q.Explain hibernate object states? Explain hibernate objects life cycle?A.

    Persistentobjects and collections are short lived single threaded objects, which store the persistent state. Theseobjects synchronize their state with the database depending on your flush strategy (i.e. auto-flush where as soon assetXXX() method is called or an item is removed from a Set, List etc or define your own synchronization points withsession.flush(), transaction.commit() calls). If you remove an item from a persistent collection like a Set, it will beremoved 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 associatedsession is closed, persistent objects become detached objects and are free to use directly as data transfer objects inany application layers like business layer, presentation layer etc.

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

    Transientobjects 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. Transientobjects become persistent objects when associated to a session by calling methods like session.save( ),session.persist( ) etc.

    http://java-success.blogspot.com/2010/12/hibernate-interview-questions-q.htmlhttp://java-success.blogspot.com/2010/12/hibernate-interview-questions-q.htmlhttp://java-success.blogspot.com/2010/12/hibernate-interview-questions-q.html
  • 7/30/2019 Java Architect Questions

    21/22

    Q.What are the benefits of detached objects?A.

    Pros:

    When long transactions are required due to user think-time, it is the best practice to break the long

    transaction up into two or more transactions. You can use detached objects from the first transaction to carry data all

    the way up to the presentation layer. These detached objects get modified outside a transaction and later on re-

    attached to a new transaction via another session.

    http://4.bp.blogspot.com/-_lA0YLJzxcQ/ToEVy_EEQoI/AAAAAAAAAEw/1FS7RWeNyHo/s1600/Hibernate_states.JPG
  • 7/30/2019 Java Architect Questions

    22/22

    Cons:

    In general, working with detached objects is quite cumbersome, and it is better not to clutter up the session

    with them if possible. It is better to discard them and re-fetch them on subsequent requests. This approach is not only

    more portable but also more efficient because - the objects hang around in Hibernate's cache anyway.

    Also from pure rich domain driven design perspective, it is recommended to use DTOs

    (DataTransferObjects) and DOs (DomainObjects) to maintain the separation between Service and UI tiers.

    Q.When does an object become detached?A.

    ?

    1

    23

    Session session1 = sessionFactory.openSession();Car myCar = session1.get(Car.class, carId)object at this stage.session1.close(); //once the session is closed myC

    you can now pass the myCar object all the way upto the presentation tier. It can be modified without any effect toyour database table.

    ?

    1 myCar.setColor(Red); //no effect on the database

    When you are ready to persist this change to the database, it can be reattached to another session as shown below:

    ?

    1

    23

    45

    Session session2 = sessionFactory.openSession();Transaction tx = session2.beginTransaction();session2.update(myCar); //detached object myCar gets re-attachedtx.commit(); //change is synchronized with thedatabase.session2.close()

    Q.How does Hibernate distinguish between transient (i.e. newly instantiated) and detached objects?A.

    Hibernate uses the "version" property, if there is one.

    If not uses the identifier value. No identifier value means a new object. This does work only for Hibernate

    managed surrogate keys. Does not work for natural keys and assigned (i.e. not managed by Hibernate) surrogate

    keys.

    Write your own strategy with Interceptor.isUnsaved( ).

    Note: When you reattach detached objects, you need to make sure that the dependent objects are reattached aswell.

    http://java-success.blogspot.com/2010/12/hibernate-interview-questions-q.htmlhttp://java-success.blogspot.com/2010/12/hibernate-interview-questions-q.htmlhttp://java-success.blogspot.com/2010/12/hibernate-interview-questions-q.htmlhttp://java-success.blogspot.com/2010/12/hibernate-interview-questions-q.htmlhttp://java-success.blogspot.com/2010/12/hibernate-interview-questions-q.htmlhttp://java-success.blogspot.com/2010/12/hibernate-interview-questions-q.htmlhttp://java-success.blogspot.com/2010/12/hibernate-interview-questions-q.htmlhttp://java-success.blogspot.com/2010/12/hibernate-interview-questions-q.htmlhttp://java-success.blogspot.com/2010/12/hibernate-interview-questions-q.html