Feb 28, 2013

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


I recommend reading eBook "Java Notes: Effective Programming & Interview" available on Amazon, and can be read using Kindle or Kindle app.


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. 
(Latest updated on March, 2014)

But I highly recommend for even a 10 years experienced Java/J2EE developer to go for online test -
http://withoutbook.com/ AND
http://www.psychometrictest.org.uk/16pf-test/
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.
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

Is Synchronization Enough?
One major purpose of using synchronization is to prevent the race condition that can cause data to be found in intermediate or inconsistent state. But when applying synchronization blocks, we need to take care of few important things - 
1. Threads might be racing prior to the synchronized section of code. 
2. Order in which threads execute the synchronized code is determined by order in which lock is granted.
3. Can we design code so that it is threadsafe with minimal synchronization. 
Atomic Classes is answer to point number 3. 

And next question can be - 

Why use Atomic Classes?
1. Simple class to perform atomic operations, like AtomicInteger allows integer value to incremented atmically. 
2. Build a complex code with no synchronization, using Atomic Classes
But note Atomic Classes not capable of providing notification's like we have in synchronization: wait/notify. 

Difference between Semaphore and Lock ?
1. Lock can have condition and only thread can acquire lock, semaphore has totally different use. Semaphore allows one or more threads to grab permits, and thus only dictates the number of threads working in parallel.
2. Lock is used where we want a piece of code to be executed by only thread. Semaphore is used when we want to limit the number of threads running in parallel and accessing some resources like for example we want only 10 threads to run at any time in parallel no matter if they share any code or data and no matter any condition; or we want to limit the number of connections, etc. 
3. No Condition variables available in semaphore.
4. Locks can be nested like once thread enters synchronized block it can call any other synchronized method on same object. In semaphore multiple acquisitions from same thread results in multiple permits.  
5. Semaphore constructor requires the number: no of permits. Semaphore has methods to return the number of total and free permits. 
6. Semaphore with number of permits equal to 1, is similar to lock. 

Difference between Cyclic Barrier and Countdown Latch ?
1. Important thing in barrier is number(which is increment till it reaches its limit) and in latch is count(which is decremented till it reaches 0). 
2. Any thread can lower the count of latch by calling countDown(), i.e. without waiting, this can't happen in barrier. 
3. Latch can't be reused. 
4. In barrier we can have a BarrierAction, nothing similar is in Latch. 

Why use Thread pool?
For better throughput. 
For eg., if 3 threads with equal priority run in time sliced manner and each one takes 3 secs to complete. Then each one will finish probably in 9 secs. But if we run these three sequentially then one will finish in 3 secs, next in 6 and last in 9 secs. And if threads are running in time sliced manner and number of threads keep on increasing, then each thread will take more time may be 30 secs for each thread if there are 10 threads. Keeping things sequential+parallel i.e., by controlling order of execution and maximum no of threads we can control delay and increase throughput

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.

How is HashMap internally implemented?
pair is stored in HashMap. Pair is an entry to hashMap. Entries are stored in an array. So we have an array of entries. 
Each Entry has a key. We calculate hash(key.hashcode()), which determines the index in array. hash method shortens the hashcode value to a valid int index. 
The value at any index in array is called bucket, which holds the Entry. 
If for two Entries index comes out to be same, while storing. This is possible if two keys have same hashCode value. Then those two entries are stored in same bucket. Bucket is a linkedlist ate any index in array, and bucket holds the Entries. So we can have multiple entries in same bucket. 
When get(Key) operation is called. We do following - 
1. Calculate the hash(key.hashcode), so that we know the index of the bucket in array. 
2. If bucket holds more than one Key, use equals(on key) to return the exact match. 

How to make existing code with Maps thread safe?
Collections.synchronizedMap might help
http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#synchronizedMap(java.util.Map)


How to implement a polling mechanism in Java. How if I want to poll something. How if client is sending some requests to server and if request doesn't arrives in within time limit or if no requests for like 2 minutes, stop expecting more requests and suspend operation/listening/waiting ?
Use Class ArrayBlockingQueue
Also, an useful method of ArrayBlockingQueue -
public E poll(long timeout,
     TimeUnit unit)
       throws InterruptedException




Difference between String, StringBuffer, and StringBuilder

1) String is immutable while StringBuffer and StringBuilder is mutable object.
2) StringBuffer is synchronized while StringBuilder is not which makes StringBuilder faster than StringBuffer.
3) Concatenation operator "+" is internal implemented using either StringBuffer or StringBuilder.
4) Use String if you require immutability, use Stringbuffer in java if you need mutable + thread-safety and use StringBuilder in Java if you require mutable + without thread-safety.

Why use Generics - 
Benefits of using Generics -
1. Stronger type checks at compile time. And thus avoid casting errors at run-time.
2. No need of casting. No extra code for casting like String s = (String) list.get(0).
3. Better, Intelligent, Generic, and good looking programming. 

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.


We have a very huge message, that we want to break into smaller parts and send. While sending we have to take care of hundereds of clients. How we can design this using JMS?
Hundreds of clients means hundreds of consumers. We have to publish the message which will be consumed by many consumers. So, we will use a topic for publishing message. 
Now since we are going to break the message in multiple parts and send them one by one. Consumer should be able to add all those parts received one by one, and constitute a final message. What we want is that consumer should be able to co-relate all those messages, and in JMS way to co-relate different messages is using CorrelationID. 

How to handle security in Java/J2EE applications?
This is a huge topic, but I have summarized some points which are most important ones in my below post - 
http://shekup.blogspot.in/2014/04/how-to-handle-security-in-javaj2ee.html

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 are 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. 


Web Development - 

Difference between JQuery and AJAX - 
Both are different. JQuery is a Javascript llibrary. AJAX is a combination of technologies , its a functionality. In order to use AJAX, you would need a client side scripting language that allows you to detect the actions of the user and modify elements on the page accordingly. jQuery does that exactly, that is why both are often used together to present web pages that a user can interact with easily without repetitive loading.  jQuery gives you an AJAX command to retrieve whichever data you need from the server.

A modern Web Application in 2014- ORM, Spring framework, REST Services, Javascript MVC framework, and probably MEAN stack. 

Others - 

What is non functional requirement? Anything related to Quality like - maintainability, scalability, etc. and related to security.
read more - http://en.wikipedia.org/wiki/Non-functional_requirement
Share:
© Shift, ShEkUP, Shape, and Surprise | All rights reserved.
Blogger Template Crafted by pipdig