Wednesday 28 August 2013

Top Most Answers and Questions for Interview when 5, 6, 7, 8 years exp. in Java/J2EE

Few years back I posted - Interview Questions when 5 or 6 years of Java/J2EE experie
Above post I wrote in 2012

I am writing this post in 2013 and in past 3 years nothing significant changed in Java/J2EE. And I am sure in coming years still the hot topics for interview would remain same like Class loading, I/O, Multithreading, NIO in core java, and JSF tag, JMS concept, EJB concept would be in J2EE. 


When I am taking interview of any 4 or 5 years java experienced person, my expectation is he should be familiar with NIO, Executer framework, Thread safety, ORM, messaging, JSF tags, web services, JSP/Servlet, and any framework. 

But if experience is 6+ then expectation is bit higher and my most preferred questions are -
Questions from Executer framework like semaphore, barrier, latch, thread pool, callable, etc. 
Thread safety, Explicit locking, etc. 
NIO
Servlets thread safety, Servlets listeners. 
ORM, why use ORM, which ORM to use, ORM with cache, problems in using ORM like Concurrency and persistence exceptions. 
JAX-WS, web services, REST, where to use REST
One framework is a must. 
Cloud computing concept and architecture. 

Messaging advanced, guaranteed delivery and integration, and where to use messaging and where to use web services. 

This post is the continuation to my previous posts related to Java/J2EE interview questions. Where I want to provide answers to questions mentioned in that post, and also add more answers -



Core Java -

-----------

50 numbers ( 1 to 50 ) are distributed in random order in an array of size 50.

One number is missing. How to find.
One approach
Sort the array. Numbers are Integer. And in the place of missing there would be default value 0.
We can iterate the array. Can take the zero's place, and the number before and after.
And we know.

Why use Inner class.

I would say Inner class is never mandatory or necessary, there is always workaround
But at some places they are convinience like in Map.Entry, Iterator inside List, or
listener in GUI.
The use is to increase encapsulation and hide some implementation details.
Classes like Semaphore use internal objects for locking, etc.

Serialization

We are writing the Java object in a file, and again creating the java object by reading bytes form the file.
Above is a kind of a persistence mechanism, but Serialization purpose is not persistence, there are DB's for that.
Use of serialization is to transfer objects over network.
We can write the Java object as byte array in memory, and later again construct the object from byte array in memory,
OR we can write the object over socket, data is sent over wire to receiving socket, and there it would be constructed again.
OR we convert Java objects in XML instances and later construct back from XML in SOAP context.
Serialization is the mechanism used by RMI to pass objects between JVMs,
either as arguments in a method invocation from a client to a server or as return values from a method invocation.
We should know how to make class Serializable, and also about interface Externlizable.


Printing alternate numbers where arraylist is getting modified 

We can get a iterator, and we might get COncurrentModificationException.
May be we should have used CopyOnWriteArrayList used to avoid that.


How to implement a Hospital scenario, where doctor is examining patients, and emergency cases,

and informing doctor of emergency cases, scheduling, etc.
We can use a priority Queue.


How to ensure only one instance in Singleton class.

class Singleton
{
  private static Singleton instance = new Singleton();

  private Singleton()

  {
    //...
  }

  public static Singleton getInstance()

  {
    return instance;
  }
}
Refer - http://www.ibm.com/developerworks/java/library/j-dcl/index.html

Synchronization -

Inside the Java virtual machine, each thread is awarded a Java stack, which contains data no other thread can access,
including the local variables, parameters, and return values of each method the thread has invoked.
All objects reside on the heap.There is only one heap inside the JVM, and all threads share it.
Besides the Java stack and the heap, the other place data may reside in the JVM is the method area,
which contains all the class (or static) variables used by the program.
To coordinate shared data access among multiple threads, the Java virtual machine associates a lock with each object and class.
A lock is like a privilege that only one thread can "possess" at any one time.
If a thread wants to lock a particular object or class, it asks the JVM.
When the thread no longer needs the lock, it returns it to the JVM. If another thread has requested the same lock, the JVM passes the lock to that thread.
The JVM uses locks in conjunction with monitors. A monitor is basically a guardian in that it watches over a sequence of code,
making sure only one thread at a time executes the code.

Each monitor is associated with an object reference. When a thread arrives at the first instruction in a block of code that is under the watchful eye of a monitor,

the thread must obtain a lock on the referenced object.
In Java language terminology, the coordination of multiple threads that must access shared data is called synchronization.
Two opcodes, monitorenter and monitorexit, are used for synchronization blocks within methods, as shown in the table below.
When monitorenter is encountered by the Java virtual machine, it acquires the lock for the object referred to by objectref
on the stack. If the thread already owns the lock for that object, a count is incremented. Each time monitorexit is executed
for the thread on the object, the count is decremented. When the count reaches zero, the monitor is released.
- See more at: http://www.javaworld.com/javaworld/jw-07-1997/jw-07-hood.html?page=2#sthash.VWVX3ZYW.dpuf

JGroup

JGroups is a toolkit for reliable multicast communication.
It can be used to create groups of processes whose members can send messages to each other
The most powerful feature of JGroups is its flexible protocol stack


Garbage Collection - 
http://shekup.blogspot.in/2011/11/java-runtime-memory-management.html



When are class garbage collected, when are classes unloaded.

The only way that a Class can be unloaded is if the Classloader used is garbage collected. 

How to ensure that instance is never garbage collected.

A singleton kind of pattern. 
There's a static reference to a singleton, so it won't be eligible for garbage collection until the 
classloader is eligible for garbage collection.

J2EE - 

------

Lightweight J2EE web application

A typical architecture for J2ee web application is
Web layer - Business Layer - Database
JSP - Servlet - Session Bean - Entity Bean
which later evolved to
JSF UI - JSF Backing Bean - EJB3 Session Bean - JPA
Or using some implementation like ADF instead of JSF
ADF - EJB3 Session Bean - JPA/Toplink
OR, if using Struts -
Struts - Business layer
OR
Spring MVC - JPA/Hibernate
OR even
JSF - Spring WebFlow - JPA/Hibernate
Some used below
Struts - Spring - Hibernate
There was a recent survey done over web frameworks, and result is Spring MVC is most adopted framework
(http://www.infoq.com/research/jvm-web-frameworks?utm_source=infoqresearch&utm_campaign=rr-content)
Now remember and note there is one very imprtant layer in the front Client Technologies
Client Technologies + Web Layer - Business layer - Persistence layer
Client Technologies include HTML, CSS, Javascript, JQuery, Ajax, JSON, DOJO, REST, FLEX, etc.

If I go more back and look into evolution


HTML(high performance poor UI)

-> CGI(dynamic content, low performance, still bit poor UI)
-> JavaScript
-> AJAX
and somewhere Applets also came.
But, Google changed the architecture of web applications, esp. when intorduced web applications like
Google Map using JavaScript, AJAX, JSON,which is a web application but looks like Desktop with amazing UI.
Google Maps used JavaScript extensively, where when user drags the map and grid squares are downloaded from the server.
And Web application architecture started thinking of making CLIENT more rich.
So, Web Architecture, which was
CLIENT(HTML) - Server(View generation - Controllers - Service layer/Business layer - Repository)
has changed to
CLIENT(HTML & JS also DOM, controllers, objects) - Server(Service layer/Business layer - Repository)
And there is a need to break big service layer into independent services,
And may be independent services are dependent on other servics coming from platform or cloud.
And now we consider where ever we can use REST.



Web Services


Different protocols for web services - 


XML-RPC (RPC) - Its a simple, portable way to make remote procedure calls over HTTP. 

An XML-RPC message is an HTTP-POST request. The body of the request is in XML. 
A procedure executes on the server and the value it returns is also formatted in XML.
Procedure parameters can be scalars, numbers, strings, dates, etc.; and can also be complex record and list structures.
HTTP request is send. No WSDL.  
(http://tldp.org/HOWTO/XML-RPC-HOWTO/xmlrpc-howto-intro.html)

JSON-RPC (RPC) - All transfer types are single objects, serialized using JSON. https://code.google.com/p/json-rpc/wiki/Usage

JSON-RPC is lightweight remote procedure call protocol similar to XML-RPC

SOAP (SOA, needs WSDL)

SOAP like XML-RPC, but lot more features, requires WSDL. 

REST

SOAP uses interfaces and named operations to expose business logic. REST uses (generally) URI and methods like (GET, PUT, POST, DELETE) to expose resources.

Managing Session in Web Services

Normally, a JAX-WS Web service is stateless: 
that is, none of the local variables and object values that you set in the Web service object are saved from one invocation 
to the next. 
Even sequential requests from a single client are treated each as independent, stateless method invocations.
Enabling stateful support in a JAX-WS Web service requires a minimal amount of coding on both the client and server.
And there can be several approaches. 
Like what we can do is - Inject WebServiceCOntext in Web service Impl class. 
We can access the HttpSessionObject from WebServiceContext. 
Save objects in HttpSession using setAttribute, and can later retrieved using getAttribute. 
(Check for more details - http://docs.oracle.com/cd/E17904_01/web.1111/e13734/stateful.htm)


EJB



How can EJB/business layer client can execute a use case's business logic in one transaction and in one call. 

EJB Session Facade pattern. 
Wrap Entity beans in a layer of session beans, and clients accessing sesison beans. 
Some precautions must be taken while designing the session facde - 
1. Avoid very big facade.
2. Avoid duplicate code in facade methods. 
I remember a design where we first wrote a Java class(AFacade) with all the implementation code. 
AFacade implements a interface ASession. and we have a session bean implementation class ASessionImpl.
AsessionImpl extends AFacade. Generally we were writing very few lines in the ASessionImpl,
since all the implementation code was already there in AFacade. 
Benefits, the business logic was also going in a separate application, a jar file.
Jar file was a batch implementation. Some clients which do not want to make remote lookup,
or are not running in the app server, were directly using the jar file. 
Same code when becomes part of EJB, there capabilities added - 
1. Its exposed for remote lookup
2. It can exposed as Web Service
3. transaction capabilities are added
4. Low Coupling
5. Clear separation of other layers(like presentation). It represents athe business layer. 
App Server provides multiple options like pooling, caching so using EJB is not a performance issue. 

How client can make a asynchronous call along with transaction capabilities. 

Message Driven Beans
A Message Driven Bean can also act as a facade. 
Client send a message to a JMS Queue, MDB's onMessage is invoked. 
onMessage can be in transaction, and if it fails, the message can be rolled back and sent back to Queue. 
Some precautions must be taken whiloe using MDB - 
1. The request, should be properly constructed. We can objects also in reuqest. 
   There are several options for request. 
2. Prevent Message loss. 
3. Transaciton handling. 
4. Exception handling, because actual exeption wont be propagated automatically to client. 
5. Response to client, because there is no automatic response send. 

How to prevent Message loss in Message Driven Bean -
Please read a small post 
http://shekup.blogspot.in/2012/02/prevent-message-loss-in-message-driven_21.html

Session Bean and pooling -  

When Server is first started, several Stateless session bean instances are created and placed in the Ready pool. More instances might be created by the container as needed by the EJB container.  When a bean instance is in the ready state, it can service client requests; that is, execute component methods. When a client invokes a business method, the EJB container assigns an available bean instance to execute the business method. Once execution has finished, the session bean instance is ready to execute another business method.  When the EJB container decides to reduce the number of session bean instances in the ready pool, it makes the bean instance ready for garbage collection. Just prior to doing this, it calls the callback method ejbRemove. If your session bean needs to execute some cleanup action prior to garbage collection, you can implement it using this callback method. The callback method is not tied to the remove method invoked by a client. For a stateless session bean, calling the remove method invalidates the reference to the bean instance already in the ready pool, but it does not move a bean instance from the ready to the does not exist state, as the management of stateless session bean instances is fully done by the EJB container.  
If all the beans form pool are active, any new client comes, it would be blocked if transaction time outs or time out occurs, Server would throw RemoteException to remote clients and EJBException to local clients. 
For stateful session bean, When a client invokes a create method on a stateful session bean, the EJB container creates a new instance.  To more optimally manage resources, the EJB container might passivate an inactive stateful session bean instance by moving it from the ready state to the passive state. When a session bean instance is passivated, its (non-transient) data is serialized and written to disk, after which the bean instance is purged from memory, and if cache is full instance would be passivated to disk. For session bean there is algo to remove the bean, like time out, where bean is totally discarded, when bean is in passive state for time longer than session time out. Unlike anonymous stateless sesison beans, stateful have identity, which is used to bound it to client. 
One important point we should know is that pool is use for stateless(either EJB or thread or anything), and cache is used for statefull(either EJB or entity or anything). 
We always prefer stateless session bean over stateful. 

EJB Transactions -  

EJB provides some options for setting the transaction. We can set the transaction attribute - 
REQUIRED Methods executed within a transaction. If client provides transaction, it is used; if not, new transaction generated. Commit at end of method. Default attribute set by WebSphere Studio. Well-suited for EJB Sessions.
MANDATORY - Client of this EJB must create a transaction in which this method operates, otherwise an error. Well-suited for EJB Entitys.
REQUIRES_NEW - Methods executed within a transaction. If client provides transaction, it is suspended. A new transaction is generated, regardless. Commit at end of method.
SUPPORTS - Transactions optional.
NOT_SUPPORTED - Transactions not supported; if provided, ignored.
Transaction attributes help us create boundaries  but they don't solve the common problems faced, obsolete data or concurrent modification. 
Some common problems related to data are - 
Dirty Reads - A transaction reads data written by another transaction that has not been committed yet. Because this data is uncommitted, a transaction failure would roll back these read changes.
Occurs when one transaction (T2) reads data that has been modified by previously started transaction (T1), but not committed
What happens if the T1 rolls back? T1 has incorrect data, thus "dirty read".
Nonrepeatable reads - A transaction rereads data it has previously read and finds that data has been modified by another committed transaction in the meantime.
Occurs when one transaction (T1) reads same data twice, while another transaction (T2) modifies the data between the two reads by T1.
T1 gets different value between the first and the second read, thus "nonrepeatable read".
Phantom reads - A transaction reexecutes a query returning a set of rows that satisfy a search condition and finds that the set of rows satisfying the condition has changed due to another committed transaction in the meantime.
Occurs when one transaction begins reading data and another inserts to or deletes data from the table being read.
Above mentioned problems are solved by setting the isolation level, which can be provided by App server or DB. 

LinkWithin

Related Posts Plugin for WordPress, Blogger...

Labels

Core Java programming core java interview question Core Java Faq's Servlets coding database jsp-servlet spring Java linux unix interview questions java investment bank Web Services Interview investment bank mysql Senior java developer interviews best practices java collection tutorial RMI SQL Eclipse FIX protocol tutorial tibco J2EE groovy java questions SCJP grails java 5 tutorial jdbc beginner error and exception Design Patterns Java Programming Tutorials fundamentals general object oriented programming xml Java Programs Hibernate Examples Flex JAMon Java xml tutorial logging Jsp Struts 2.0 Sybase and SQL Server debugging java interviews performance FIX Protocol interview questions JUnit testing WebSphere date and time tutorial experienced java IO tutorial java concurrency thread Ejb Freshers Papers IT Management Java Exapmle Java Script SQL and database tutorial examples Scwcd ant tutorials concurrency example and tutorial future state homework java changes java threading tricky Agile Business of IT Development JSTL Java JSON tutorial Java multithreading Tutorials PM Scrum data structure and algorithm java puzzles java tips testing tips windows 8 5 way to create Singleton Object Architect Interview Questions and Answers Architecture Architecure Bluetooth server as swing application that searches bluetooth device in 10 meter circle and show all devices. You can send file to any bluetooth device. C Programming CIO Callable Statement in Java Circular dependency of Objects in Java Comparable Example in Collection Custom annotation in Java Developer Interview Divide and rule example in java Drupal Example of Singleton Pattern FIX protocol ForkJoin Example in Java 7 Get data from dynamic table with Java Script Git HTML and JavaScript Health Hello World TCP Client Server Networking Program Hibernate Basics Hibernate Interview Question Answer J2EE Interview Question And Answers J2ME GUI Program JEE Interview QA JMS interview question Java J2EE Hibernate Spring Struts Interview Question Java System Property Java Threads Manager Portlets Provident Fund Read data from any file in same location and give the required result. Reading Properties File in Java Redpoint Rest WebService Client Rest Webservice Test SAL join with ven diagram SCP UNIX COMMAND SSL Singleton Pattern in Java Spring Bean Initialization methods and their order Spring Interview Questions Struts Struts 2.0 Basics Struts 2.0 Design Pattern Submit Html Form With Java Script On The Fly Unix executable For Java Program XOM DOM SAX XP books computers core java; core java; object oriented programming data structure; java investment bank; design pattern dtd duplicate rows in table get browser name with jquery grails podcast inner class java beginners tutorial java cache java networking tutorial java spring java util; java collections; java questions java.java1.5 linked list mailto function with all browser oracle database oracle duplicate rows orm schema social spring mvc questions struts transaction tricks tweet windows xslt