Feb 28, 2013

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


I wrote a post in 2012- Interview Questions when 5 or 6 years of Java/J2EE experie
Then I wrote this post in 2013 and untill 2014 nothing much changed. 
I have updated the post in Jan, 2018 because I saw many changes between 2015 and 2017 especially due to rise of Microservices, Cloud, and Big Data. 

I have updated my eBook in 2018, which one can download for free from slideshare. Please feel free to share the feedback so that I can update the book and this post.


https://www.slideshare.net/AUpad/java-notes-effective-development-and-interview

Focus of this post is on Microservices, Core Java, and Java EE.  

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/

In 2014, When I am taking interview of any 4 or 5 years java experienced person, my expectation is he or she should be familiar with NIO, Executer framework, Thread safety, ORM, messaging, JSF tags, web services, JSP/Servlet, and any framework.  Now I expect Spring Boot, Dockers, Cloud, Big Data, and AWS.  I will also prefer a Java programmer to be aware of Java fundamentals such as: 
  • 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, JAX-RS
  • Spring 
  • Cloud computing concept and architecture. 
Microservices is really critical because its an ecosystem and not now limited to REST and JSON.

Micro-services

Microservices is big topic because recently I was working in an organisation with legacy infrastructure and I wanted to implement microservices.  It is not easy to transform legacy to microservices (RESTful) and it seems SOA (ESB, Messaging and Web services) is more suitable.  Also, one tough question is how big or small microservice should be.  Few points: 

Microservices are not replacement of SOA and they both still apply can work together. Read more on https://www.ibm.com/developerworks/websphere/library/techarticles/1601_clark-trs/1601_clark.html

What is microservice? Some of the common characteristics of Microservices (Nadareishvili, et al., 2016 p. 25) Small in size, Messaging enabled, Bounded by contexts, Autonomously developed, Independently deployable, Decentralized

Scalable: The Microservices Architecture pattern corresponds to the Y-axis scaling of the Scale Cube, which is a 3D model of scalability from the excellent book The Art of Scalability. The other two scaling axes are X-axis scaling, which consists of running multiple identical copies of the application behind a load balancer, and Z-axis scaling (or data partitioning), where an attribute of the request (for example, the primary key of a row or identity of a customer) is used to route the request to a particular server (Richardson, et al., 2016 p. 6)

Complexity: Microservices architecture is complex and it requires expertise & tools to manage the complexity.   Challenges of microservices (Richardson, et al., 2016 pp. 9,10)
  • 10-100 Line Of Code Services: While small services are preferable, remember goal is not small services instead agility.  How big or small is not fixed but definitely it is not on resource level in my experience such as create 100 tables and 100 RESTful microservice with CRUD operations.  Instead consider four options: Bounded Context (smallest business function or process inspired by business units within organisation), Business Capabilities (such as exchange rates), CRUD (User), and Service (Authentication, OTP, and so on)
  • Communication: IPC via messaging and/or RPC, Netflix relies on message formats like Avro, Protobuf, and Thrift over TCP/IP for communicating internally and JSON over HTTP for communicating to external consumers (e.g., mobile phones, browsers, etc.).  Communication can be one-to-one or one-to-many and communication can be synchronous or asynchronous. 
    We can use a message broker to deliver event notifications from microservices in an asynchronous manner. That said, letting microservices directly interact with message brokers (such as RabbitMQ, etc.) is not a good idea. If two microservices are directly communicating via a message-queue channel, they are sharing a data space (the channel).  The message-passing workflow we are most interested in, in the context of microservice architecture, is a simple publish/subscribe workflow: PubSubHubBub
  • Partitioned Database: Eventual consistency approach with event sourcing and CQRS
  • Testing: With Spring boot its trivial but don't underestimate
  • Implementing changes across services: fortunately changes that require coordination across services should be rare or less but it is design challenge
  • Deployment: many instances of many services with hosts and ports along with service discovery.  Two approaches - Cloud Foundry and Kubernetes in conjunction with Docker
  • Data Sharing: Sharing data creates tight coupling between microservices, which kills their mobility; therefore data sharing between microservices is to be avoided. Prefer topics over queues and let microservices manage their repositories (private databases of microservices). However, sharing a database cluster installation or overall messaging system is absolutely OK, given that each microservice only accesses isolated, name spaced portions of it.
  • Managing data: If approach is that every microservice will own its database, then That service is the canonical system of record for that data.  Every other copy is a read-only, non-authoritative cache. How to manage data: Synchronous lookup (services call each other whenever required Customer service calls account service for account info), Asynchronous events and local cache by services (Customer service maintains a cache of Account details and send notification to Account service when Customer info is updated so that Account Service can update its cached Customer Info), Shared metadata library (read only, generally immutable data such as list of countries), Joins (Client application or another service - Aggregator - can aggregate data from several services)
  • Transactions: Model the transaction as a state machine of atomic events - As a workflow - Transaction Saga with Routing Slip
  • Navigation: Hypermedia driven microservices can help client applications with navigation 
  • Message Format: Text (JSON/XML) or Binary (Thrift, Protocol Buffer, Apache Avro)
  • Independent Deployability: A combination of Approach & Strategy - 
    • Each Java service with embedded tomcat
    • Few services on one tomcat
    • Service instance per Virtual Machine (each service is independent EC2 instance in AWS)
    • Service instance per container (Java code & tomcat as a image that is replicated - multiple containers (dockers) - across VM; containers are managed using kubernetes); Noe Container images are faster to build compared to VMs; Unless we are using a hosted container solution such as Google Container Engine or Amazon EC2 Container Service (ECS), then you must administer the container infrastructure and possibly the VM infrastructure that it runs on.
    • Serverless - AWS Lambda is an example of serverless deployment technology. To deploy a microservice, we package it as a ZIP file and upload it to AWS Lambda. We also supply metadata, which among other things specifies the name of the function that is invoked to handle a request (a.k.a. an event). AWS Lambda automatically runs enough instances of our microservice to handle requests. We are simply billed for each request based on the time taken and the memory consumed.  Notion is we as a developer need not worry about any aspect of servers, virtual machines, or containers.
  • Service Discovery: IP address & host of each service at runtime and how services know each other.  Kubernetes, Docker Swarm, and Mesosphere help here.  In AWS, ELB is server side service discovery approach.  The AWS Elastic Load Balancer (ELB) is an example of a server-side discovery router.  ELB is commonly used to load balance external traffic from the Internet. However, we can also use ELB to load balance traffic that is internal to a virtual private cloud (VPC). A client makes requests (HTTP or TCP) via the ELB using its DNS name. The ELB load balances the traffic among a set of registered Elastic Compute Cloud (EC2) instances or EC2 Container Service (ECS) containers. There isn’t a separately visible service registry. Instead, EC2 instances and ECS containers are registered with the ELB itself.  Netflix has client side discovery custom tool: Netflix OSS along with Netflix Eureka as service registry.  Kubernetes and AWS don't have explicit Service registry instead they maintain internally. 
  • Gateway: Mature API Gateway provide secure endpoints, orchestration and transformation, reduce latency, optimize payload (response from N+1 service calls to client)
  • Handling Partial Failure: Netflix blog has several approaches such as timeout, circuit breaker pattern   
Microservices come with lot of complexity that is it is an ecosystem and therefore microservices interview will be comprising definitely of Spring Boot, Docker/AWS/Kubernetes, Kafka/rabbit MQ, and so on.

I was asked in an Interview to create a very simple microservice application.  These days (2017-18) while taking interviews I am also asking to build microservice (on paper) for a use case: Manage users and expose REST APIs.  I created a sample application and I expect similar. Please feel free to go through the application:  Spring boot demo project

References and Recommendation
COCKCROFT, ADRIAN. 2015. ADRIAN COCKCROFT TO SPEAK @ DOCKERCON 2015. docker blog. [Online] May 2015. https://blog.docker.com/2015/05/adrian-cockcroft-to-speak-dockercon-2015/.
Nadareishvili, Irakli, et al. 2016. Microservice Architecture Aligning Principles, Practices, and Culture. 2016.
Richardson, Chris and Smith, Floyd. 2016. Microservices from Design to Deployment. s.l. : NGINX Inc., 2016.
Wolff, Eberhard. 2016. What Are Microservices? informIT. [Online] 2016. 



Messaging is important in microservices and modern tools are very very efficient.  Concepts of JMS are still valid and applicable to any messaging tool - Messaging guidelines, Guaranteed delivery and integration, and where to use messaging (topic or queue) and where to use web services (SOAP or REST). 


Core Java

One of the most complicated and interesting part of Core Java is Executor framework and understanding it will definitely help as a role of Developer or Architect.  It is very well written and a marvel.  I would recommend reading book "Java Threads" book - http://shop.oreilly.com/product/9780596007829.do
A solid understanding of Locking, thread pool, and performance is important.
For performance, I recommend watching video on InfoQ -
https://www.infoq.com/presentations/java-performance-guide

Random questions are
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.  It 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. 

Why use Atomic Classes?  A Simple class to perform atomic operations, like AtomicInteger allows integer value to incremented atomically.  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. 

Java EE


Java EE is a platform to build a multi-tiered and distributed application.  The platform provides API’s to build all tiers of application : Client tier components that run on client machine such as web page.  Web tier components that manage the web pages, flows of web pages, and handle request & response from client tier.  Business tier component run on server and behind firewall.  They have the business logic such as logic to transfer fund, retrieving customer details, and so on.  Enterprise Information System (EIS) running on EIS server such as database or file system

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 introduced 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) along with need to break monoliths into microservices. 

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 was- ORM, Spring framework, REST Services, Javascript MVC framework, and probably MEAN stack. and then came Spring boot, but spring boot alone was not sufficient instead Docker was the key to success of microservices.  Dockers required management, which is done by Kubernetes.  Big Data and Data Science are suitable for Scala.  One thing I would recommend from my experience is if you Java programmer focus on Scala and do not try to learn Python for Machine Learning and AI programming.  I spend last whole year learning Python and trying to write AI programs and it is too complicated and very very different.   Technology is fast changing and right now but some of the important technologies right now to focus are: Spring Boot, Serverless, Scala, Lucene, Kafka, and so on.  Domain Driven Design is important right now and I believe everyone should read the book by Eric Evans.  

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

Below are the some questions for a team leader. Obviously, these are very few. I would add more later. 

1. On the occasion of some festive season, there is some deadline, and there are some pending works, but most of the team members have already planned for holidays. How are you going to manage, means manage delivery, even when you have also leave plans. 


2. Have you ever faced a situation, where you needed to go beyond company policies, means you needed to break them in order to get things done, what did you do, and if you broke company policy what was the impact.

3. Did you ever exceeded the client and/or company expectations, when and how. 

4. What is more important to you Delivery or Status reports by team members. 

5. You have a situation, where you need to give appreciation, probably salary increment to only one among three of the team members. You know rest two are good, what reason you are going to give, when you know there is no genuine reason to give them.

6. Explain Agile

7. What is difference in managing a Contractor and Permanent resource

Lastly, I have updated my eBook in 2018, which one can download for free from slideshare. Please feel free to share the feedback so that I can update the book and this post.

https://www.slideshare.net/AUpad/java-notes-effective-development-and-interview

Share:

5 comments

  1. please elaborate with example priority queue in hospitality project?

    ReplyDelete
  2. http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html
    And below I found a nice example of priority queue -
    http://www.javacodegeeks.com/2013/07/java-priority-queue-priorityqueue-example.html

    ReplyDelete
  3. For Core Java question there can be one more approach:

    In mathematics, sum of n number is n* (n+1)/2. In given example n=50 so sum is 50* 51/2=1275.

    Now iterate over the array and do sum of the numbers given in array.

    Missing number = sum of n numbers - sum of numbers in array.

    ReplyDelete
  4. Replies
    1. There is one issue while you write Singleton class . You made static private variable of same class. That variable can be instantiated multiple times from same class breaking singleton class rule.

      Delete

Comment

© Technology Strategy, Architecture, and Development | All rights reserved.
Blogger Template Crafted by pipdig