Home » TechBlog

Category Archives: TechBlog


readObject() and writeObject() &nd; readResolve()

There is, however, a strange yet crafty solution. By using a built-in feature of the serialization mechanism, developers can enhance the normal process by providing two methods inside their class files. Those methods are:

  • private void writeObject(ObjectOutputStream out) throws IOException;
  • private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;

Notice that both methods are (and must be) declared private, proving that neither method is inherited and overridden or overloaded. The trick here is that the virtual machine will automatically check to see if either method is declared during the corresponding method call. The virtual machine can call private methods of your class whenever it wants but no other objects can. Thus, the integrity of the class is maintained and the serialization protocol can continue to work as normal. The serialization protocol is always used the same way, by calling either ObjectOutputStream.writeObject() or ObjectInputStream.readObject(). So, even though those specialized private methods are provided, the object serialization works the same way as far as any calling object is concerned.


readResolve is called after readObject has returned (conversely writeReplace is called before writeObject and probably on a different object). The object the method returns replaces this object returned to the user of ObjectInputStream.readObject and any further back references to the object in the stream. It is mostly used for serial proxies for example in case is Singleton class if it is serializable then we need to specify in readResolve that it returns singleton object and not the one which is read from persisted location.


Key notes of Singleton Pattern

Singleton has been one of the most discussed pattern in interviews. These are some key points while writing singleton pattern.

  • Only one object instance is required.
  • Synchronization of getInstance() or only critical section: It is recommended to keep only object creation part in synchronised section to reduce the overhead as it is costly.
  • Lazy or early initialisation: Well if you need object should only be initialized when first time getInstance method is called, this is called lazy initialisation. If object is required to be preloaded then we can use a static block to load the instantiate.
  • DoubleCheck : This is a mechanism to ensure only one object is created while calling getInstance method
    public static SimpleSingleton getInstance(){
    		//double null check
    				_INSTANCE = new SimpleSingleton();
    			System.out.println("Object created");
    		return _INSTANCE;
  • How to prevent cloning: If singleton class is not extending any class then if you do not implement cone method; that is enough to prevent cloning of object of singleton class. If Singleton class is extending any class then optionally you can override its clone() method and you can throw CloneNotSupported exception out of that.
  • Ensure Object is not serializable. As we know that Deserialization can bypass the constructor call and object can be instantiated (Only if class implements Serialization interface). So if we are giving an option to serialize a singleton object then we need to enforce not to read stream object. readResolve method is called when ObjectInputStream has read an object from the stream and is preparing to return it to the caller. ObjectInputStream checks whether the class of the object defines the readResolve method. If the method is defined, the readResolve method is called to allow the object in the stream to designate the object to be returned. The object returned should be of a type that is compatible with all uses. If it is not compatible, a ClassCastException will be thrown when the type mismatch is discovered.
            public Object readResolve(){
    		return getInstance();
  • Using Static Inner class in Singleton pattern: Technically it would be treated by a thread as happens before relationship  which you can say as thread safe approach. But the same thing can be done by a static block with pre initialization of singleton object.
    public class Singleton  {
           public static final Singleton _INSTANCE ;
           //1: Simple way of getting object 
           public static Singleton getInstance() {
              if (null == _INSTANCE) {
                    _INSTANCE = new Singleton();
              return _INSTANCE;
           //2: using Static inner class approach
           static Singleton getInstance(){
              return SingletonHolder._INSTANCE;
           static class SingletonHolder{
    	   private static final Singleton _INSTANCE = new Singleton();
           //3: using static block pre initialization approach
           static {
             _INSTANCE = new Singleton();
           public static final Singleton _INSTANCE = new Singleton();
  • Making Singleton object Immutable:

Generate and Send an Excel file from J2EE WebApplication

Generating Excel file in J2EE Server.


This article is written to describe a simple way of generating an Excel file in Java. We will be using an open source Java Excel API  ( jxl http://jexcelapi.sourceforge.net/ ) to dynamically generate an excel file and reading and modifying an existing excel file.


Using this technology we can directly generate an Excel file on the fly on a user request.

In a typical web application a user can request for an excel sheet based report from a web based application.


With the proper integration of this API and the server side backend data layer, we can transform the fetched data into an excel sheet. Later this excel sheet can be sent to client side using proper http response header information.


To begin with the application we need to download the jxl.jar file and put it under the project folder.  To download go to the URL: http://sourceforge.net, and under File section you have a link to download the required jar files.



Code side view:

We may need following classes depending on our need:


import jxl.Workbook;

import jxl.format.Colour;

import jxl.format.UnderlineStyle;

import jxl.write.Label;

import jxl.write.Number;

import jxl.write.WritableCellFormat;

import jxl.write.WritableFont;

import jxl.write.WritableSheet;

import jxl.write.WritableWorkbook;

import jxl.write.WriteException;

import jxl.write.biff.RowsExceededException;



2) Create workflow object:

WritableWorkbook  wrtWorkbook = Workbook.createWorkbook(new


WritableSheet sheet1 ;


This function will create a writable workBook object. We can specify the location of the Excel file otherwise it will create in the current running folder. Later using defined API’s we can add worksheets on this workbook.

Note in case on reading excel sheet, we need to create WorkBook class

Object not WritableWorkBook.



3) Create worksheet :

sheet1 = this.wrtWorkbook.createSheet(“Sheet1”,0);

params: sheetname and location.

Here we have created a worksheet for the workbook, minimum one worksheet is required for a workbook to write some data in it. Like an Excel file one workbook can also contain more that one Sheet.


4) Adding cells :


Once the sheet object is created, we will use following API to write data in the specified cells. Here we are giving very simple demonstration but if require it also supports various kind of formatting.

To add number

Number number = new Number(colIndex, rowIndex, num);



To add string

Label label = new Label(colIndex, rowIndex, str);



5) Formatted Data

We can also specify specific format by using defined format classes:

WritableFont times10font = new WritableFont(WritableFont.TIMES, 10, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BROWN);


WritableCellFormat times10format = new WritableCellFormat

Label label = new Label(colIndex, rowIndex, str, times10format );



6) Closing Worksheet

wrtWorkbook.write(); this function will write sheet into workBook




Sending an Excel file along with the HTTP Response.


In a typical J2EE web application an http Request is processed in doGet\doPost method and a response is generated and send back to the client. We need to set response header to provide specific information about the content it carrying, so that browser can automatically detect the compatible application to open that.

resp.setHeader(“Cache-Control”, “max-age=30”);



application/vnd.ms-excel defines that it is an excel spreadsheet application.

We can defile to send content in inline format or as an attachment.

resp.setHeader(“Content-disposition”,“inline; filename=MyExcel.xls);


here using java.io API’s we will write Excel file content in the response object.


ServletOutputStream sos = response.getOutputStream();

FileInputStream fio = new FileInputStream(“./” + “MyExcel.xls”);


while((c = fio.read()) != -1) {




And that’s all. Its all set and Please go and receive the Excel file in the client’s browser.






RFID Radio Frequency Identification.

What is RFID .

Radio Frequency Identification (RFID) is an radio waves sensor technology, relying on storing and remotely retrieving data using devices called RFID tags readers. An RFID tag is a small chip that can be attached to an object it could be a simple box or an animal, or person for the purpose of identification using radio waves. Chip-based RFID tags contain silicon chip and antenna. Passive tags require no internal power source, whereas active tags require a power source.
Types of RFID tags
Passive RFID tags have no internal power supply. A minute electrical current is induced in the small circuit as it is brought in the special magnetic region, generated by the tag Reader. This small power is sufficient to em-mite the response signals. Which can be traced by the Reader.

Unlike passive RFID tags, active RFID tags have their own internal power source which is used to power any ICs that generate the outgoing signal. Active tags are typically much more reliable than passive tags due to the ability for active tags to conduct a “session” with a reader. They are more reliable in magnetic field ore naturally challenged region.

The RFID system
An RFID system may consist of several components: tags, tag readers, edge servers, middleware ( eg. Sun Java System RFID Software, IBM RFID Middle-ware), and enterprise application software.
The purpose of an RFID system is to enable data to be transmitted by a mobile device, called a tag, which is read by an RFID reader and processed according to the needs of a particular application. The data transmitted by the tag may provide identification or location information, or specifics about the product tagged, such as price, color, date of purchase, etc. RFID is being so popular because its ability to track moving objects. As the technology is refined, it is being used in different areas like asset tracking, transportation, inventory management, defense, health care etc. ..


How to develope a RFID prototype application

To develope a RFID prototype, companies like Java, IBM , sybase are we provideing their middleware . Sun has its SUN RFID 1.3 package , similarly IBM is also providing a framework to develope, test and deploy a rfis solution. IBM provides a architecture comprising Device developer kit ( will be used to develope edge controller which will controll rfid related hardware), RFID premises server which works between edge controler and your enterprise application.

feel free to ask more queries\details on RFID :