Tuesday, August 25, 2015

Java program to convert numbers to words



Output -

5='Five'
16='Sixteen'
50='Fifty'
78='Seventy Eight'
456='Four Hundred Fifty Six'
1,000='One Thousand '
99,999='Ninety Nine Thousand Nine Hundred Ninety Nine'
199,099='One Lakh Ninety Nine Thousand Ninety Nine'
10,005,000='One Crore Five Thousand '

Tuesday, June 23, 2015

JSch - Upload/download files from remote server

We will using JSch to connect our unix box. Once connected you should be able to upload or download the required files.

JSch is a pure Java implementation of SSH2. To know more click here.

For running below code you need to add jsh jar file (e.g. jsch-0.1.53.jar) in your applications classpath. Download jsch-0.1.53.jar from here.

Please see the self explanatory code below -


Tuesday, June 9, 2015

Serialization problem with Singleton

In previous example we have seen the basics of singleton. In this example we will see how Serialization can effect the Singleton design pattern.

Sometimes in distributed systems, we may need to implement Serializable interface in Singleton class so that we can store it's object state in a file system and retrieve it at later point of time. Let's take an exammple of Clipboard class which implements Serializable interface.

Clipboard.java


TestClipboard.java


Output :
c1 hashCode = 28117098
c2 hashCode = 13495805

From the above hashCode output we can see the intent of singleton pattern is simply blown up, to overcome this problem we need to provide the implementation of readResolve() method as shown below.


Now if u see the hashCode output, it will be same.

The readResolve method is invoked by serialization if the method exists and it would be accessible from a method defined within the class of the object being serialized. Thus, the method can have private, protected and package-private access. Subclass access to this method follows java accessibility rules.

Classes that need to designate a replacement when an instance of it is read from the stream should implement this special method with the exact signature - ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;