Java Code Geeks

Wednesday, November 26, 2008

Sequence Diagram - when and why

Even till recent past, I was not a fan of Sequence Diagram. I always thought if I have proper class diagram and have a fair idea on the "Use Case", I do not really need to draw a Sequence Diagram.
Its only recently I discovered that if I draw sequence diagram of a system, sometimes its become very clear which are the "chatty-interfaces". This in turn can help us to improve performance by reducing "round-trips". If we draw a sequence diagram, the interactions between the components get clear which sometimes lead to identification of "chatty-interfaces". This might sound obvious that we know how many times we are sending requests to database or webservices and the request is going over the network, but in a complex application, it might not be very straight forward. It becomes very easy to see how many times we are going across network if we draw the sequence diagram. This in turn can help us to improve the design by introducing "Caching" and reducing round-trips across networks.

Saturday, November 22, 2008

Cache vs Pool, when and why?

Cache and Pool both are very related topics in J2EE world. We use these techniques to improve performance. For example, we try to Pool the JDBC connection as opening a Database connection is costly. Similarly we Cache data in the form of objects in memory to reduce the "round-trip" time across network.
Note the way we used Pooling at one place but Caching in another place. Question is when we pool and when we cache ? We do Pooling when the objects we pool have no state in them. We do Caching when objects have states. For example, any JDBC connection object will be sufficient for the application to connect to the database. It does not matter which one is giving you the service. Hence we Pool them. But in another case, when we are looking for objects from database, lets say we have read the Customer information from database and stored them in the forms of objects in memory, in this case, we do not want any Customer object to see but we want a specific customer object whose customer id is X or whose name is 'XYZ Inc'. So the easier way to remember is - stateless information can be pooled and stateful information needs to be cached.

Friday, November 21, 2008

Command Design Pattern in J2EE

Command is one of the oldest design pattern which exists from the days of SmallTalk. It is popular for its simplicity and yet the power. The heart of this pattern is its command interface which can have simple methods like init (), execute(). The concrete command objects will implement this interface. This design pattern can take a request and pass that to the proper object for being processed without any knowledge from client. The client code does not need to know actually which concrete object is going to process this request.
In J2EE world, to adhere to MVC model, there are several design patterns available to wrap the business logic or model. For example, EJB uses Facade Design pattern and hides the model complexities from controller. Similarly Struts framework uses something called "actions". If you do not want to use EJB or Struts type of framework, yet want to adhere to MVC model, its best to use Command Design pattern. Here is a small description how -

Develop some command beans which needs to have series of Set methods to set the parameters, a series of get methods to get the results after the processing, one init method to initialize (like open JDBC connection etc) the environment before processing start and finally one execute method to really perform the processing.

Develop one command interface which will have init and execute method so that the Controller Servlet can use this interface to send the processing request without really knowing which concrete command object will process it.
Lot of time we can use Class.forName to initialize the concrete command object. For example, in the controller servlet we can have some code like this -

DBCommandBean command = (DBCommandBean)Class.forName("com.mycom."+requestType+"CommandBean).newInstance();
command.set(hashtable) -- hashtable contains some parameter and value which will be used for processing.
command.execute() -- this will perform the real processing
command.get() -- this will give back one hashtable with key and value pairs which need to be accessed to see the result of the processing.

Sunday, November 16, 2008

Distributed Transaction in J2EE framework

Distributed transaction is a fascinating topic. Think about developing a software application which needs to manage multiple databases. We usually develop software that talks to only one database in a single transaction. This is called as local transaction. If one transaction encompasses multiple databases, it is known as Distributed transactions. The distributed transaction is possible through the usage of JTA - Java Transaction API.
Before we discuss more, lets get the definitions of some terms correct -




Resource - Thnk about this as a database or JMS Queue.
Resource Manager - Its the JDBC Driver which manages the Resource - like database.
Transaction Manager - It manages the transactions across resource managers.
Transaction originator - its the client code that starts the transaction.


The transaction originator is the EJB beans that kicks off the transaction. EJB containers support distributed transactions through a protocol called "Two Phase Commit". In case of two phase commit, the Transaction Manager sends a request to all the resources before really committing the transaction. If the response is OK from all the resource managers, the transaction gets committed in the second phase or else get rolled back.

The beauty of distributed transaction is that, the transaction manager can propagate the "Transaction Context" from one Resource Manager to other Resource Manager. And all this happens in the background at the EJB Container level. Of course, your container needs to support this feature, like WebLogic Server supports distributed transactions and the two-phase commit protocol for enterprise applications.

Wednesday, November 5, 2008

Whats happening in web service world?

Web service is being a very cool mechanism to make heterogeneous systems to talk to each other. It is really powerful and so its being a hit. Since this technology is widely used, its common to find tons of evolving concepts in and around web service. Web service makes possible to send SOAP messages over any transport protocol. Heterogeneous system talk to each other by exchanging those SOAP based XML documents. JAX-RPC based web services were mainly focused on calling remote procedures using SOAP over http. Slowly people found the real power of web service is not really to call remote procedures but to exchange certain XML documents over http/SMTP/TCP etc. Hence the newer specification is called as JAX-WS which supports - REST based web service, request-response based services, asynchronous services etc.
But there are lot of improvements are happening around web service. For example, web service gateway - this technique helps enterprise to expose their internal web service to the external world. Web Service aggregation - this helps to aggregate many number of smaller web services to one bigger one. SOAP OVER JSMS - this is also very interesting as HTTP being unreliable transport mechanism, if B2B communication is happening where reliability is necessary, use JMS instead of HTTP as transport mechanism of the SOAP messages. JMS will make sure that the SOAP messages are sent to the other end (it will persist the SOAP message and if communication fails, it will resend the message again).
There is another interesting JSR called - WSRP web service for remote portlets. This allows one portal server to consume local portlets as well as remote portlets through web services.
I am really thrilled to see all of these developments around web services.

Sunday, November 2, 2008

Hibernate - great tool - greater responsibility

I really like the movie "Spiderman" and the way Peter Parker was told - "With Great Power comes Great Responsibility". Similarly Hibernate is a great tool. It has awesome capabilities in transforming "Relational Database Tables" to "Set of related objects". But we, the developers need to be responsible of how to use this tool effectively. Performance of the application can become worse if we are not careful enough with different options available in Hibernate. Here are the list of items which I found are useful to know while developing complex database oriented applications.

1) The famous n+1 problem - Hibernate usually fetches the associations lazily (lazy = true is by default). For example, if one Node can generate any number of events. In this case, hibernate will load the events for the Node only if we need the events. This is a very nice feature otherwise if you ask to load all the nodes , hibernate would have loaded all nodes and its associated events (the complete db) in the memory which will lead to "out of memory" error if the events are really large in number. So lazy loading is really a nice feature. But if you have to traverse all the nodes and process all the events - it will fire n+1 (where n is the number of nodes) to the database leading it to inefficient.
More efficient approach could be to use "batch size" option of hibernate which will make the db round trips from n+1 to n/batch_size + 1.
Another option could be to use outer-join which will fetch all the associated data using an database outer join.
Or else probably better approach is to use FetchMode.EAGER at the runtime (not in the xml file) which will load all the associated objects at once.

2) the lazy fetching can cause another problem with MVC architecture. In our case, the events of the nodes will be loaded lazily, but if we are using one DAO layer which will open the hibernate session, load the node and send that node object to the JSP file, when JSP will try to access the events of the node, it will throw one lazyinitialization exception. There are many ways to solve it and one of the most useful way is to use - Filters or one can load the association eagerly.