Wednesday, July 23, 2008

Single Instance From Your Application ?

Introduction:

some people want to have only single instance running from their application and if the user clicked/started the executable file for the application again nothing will happen or the user will be prompted that there is an already running instnace(something like MSN you only have one instance an no matter how many time you click the MSN exe icon you will just get the same instance).


Chit Chat at a cafe':

one day four programmers were having a coffee break and one of them was having a bad day trying to make a single instance from his application

programmer 1: uffff i cant enjoy my java coffee :(

programmer 2: oh why is that ?

programmer 1: i want the user only to have one instance from my application and no matter how many time he run the application he will just get one instance.

porgrammer 2:oh come on it is not that hard i have done something like that and here is what i have done :why don’t we use file a config. for example and set value in the file to indicate that there is already running instance or even create a file named for example blabla.lock and by this way i can know that the application has an instance running already and when the application is done just change the value or delete the lock file to indicate that it is done and no instance is running.

programmer 3: opps hey programmer 2 i think you have a problem in your approach

programmer 1: oh really ! what is it ?

programmer 3 : well what if the machine crashed ?you will still have the value that indicates that there is an instance running from your application.

programmer 1 : mmm you are right , i was thinking to improve my solution by using registry entries :( ohh and how can we solve such thing programmer 3?

programmer 3: well you can use sockets for that ! how is that ? let me tell you ,just connect to a port and try to listen on this port and when you click on the application icon again to start up new instance it will just go and try to listen on the same port it will get exception (as there should be only one application listening ) .

programmer 1 , 2 : ohhh :O wow nice one

programmer 3: now we can enjoy our coffee :D

programmer 4: (shaking his head) well cant we just make a better solution ???


Make a room for Programmer 4:

programmer 1,2,3 : huh what do you mean ?

programmer 4: well didnt you hear semaphore thing ?

programmer 1,2,3: huh yea but what does it have to do with our case ?

programmer 4 : well it can solve your problem but i will you another way to do so

programmer 4: Semaphore this is the magic word , in old days C++ developers used to do so (use semaphore in order to make only one instance from you application) so when you start my application there will be lock acquired and when i try to start another instancei will check for this lock if it is not acquired so this mean that i am the first instance else am not and i should throw exception or so.

programmer 1,2,3 :oh so how will we handle this issue then we didnt get the solution and our coffee is getting cold :( ?

programmer 4: (while drinking his coffee) well we can achieve the desired functionality through locking mechanism from files introduced in java.nio package.

programmer 1,2,3 : ok tell us how can we do this

programmer 4: we will acquire a lock on the file (lets say our main class file) and when our main starts it will try to acquire lock on this file. if it succeeds this mean that it is the first instance of our program and if it fails (due to already exist lock ) this mean that it is not the first instance of our application note that we will release the lock once we end the application and there wont be any hurm if the application crashed or so as we can re-start it and it will work just fine.

programmer 4: ok does any one have a paper and a pen ?

programmer 1,2,3: (the three in the same voice) sure here you are

programmer 4: ok let me write the code for you

RandomAccessFile randomFile=new RandomAccessFile("C:/myMainClass.class","rw");
FileChannel channel=randomFile.getChannel();
if(channel.tryLock()==null) //we couldnt acquire lock as it is already locked by another program instance)
System.out.println("Sorry but you have an already running instnace from the application");

programmer 4: here you are

programmer 1,2,3 : WOOOW we didnt know that, this looks like a magic

programmer 1: yepiiii hey seems that i will leave early today from my work :D , although the coffee is cold now but i still enjoy it ;)

Read more!

Monday, July 7, 2008

Singleton Tips and Tricks

Introduction:

Singleton ? what is that ? i guess i have heard someone talking about it mmm but i don't know what does it mean :( , ok don't be sad cheer up we are going to talk about Singleton and some tips and tricks for it. so lets start by defining Singleton.

A singleton is a class that is instantiated exactly once no more no less, so this mean i only have one
unique instance from a specific class that is used by the whole application so it will be the same for all objects, in other words lets assume that i have a ball (red one :D ) and that ball is with me and i wrote my name over it after that my friend shout at me and say "ball !" i will just pass the ball i have to him, so now he has my ball (which i wrote on it my name) so this is what singleton like i will just have a single unique instance (ball in our case) from a specific class.

ok great now how can i achieve that?

in order to do so we need to keep our constructor (the class we want to get only a single unique instance) private and provide a public static instance that will allow the user of our class lets check the following example

public class myClass
{
private static final myClass myclass =null

pirivate myClass()
{
}

public static myClass getInstance()
{
if (myclass==null)
return myclass=new myClass();
}
}

ho ho now we are done right ? nope not exactly , you have created a singleton and congratulations for that ;) so when i need to get instance from myClass i will do so

myClass instance=myClass.getInstance();

You :ok ok now tell me that we are done ok?
Me :nope sorry there is a missing thing.
You: Missing thing?
Me: yes, what do you think if there are two threads invoked the getInstance at the same time? what will happen ?
You: explain more.

Meet Mr. Scheduler(The Problem):

ok now you are calling the getInstance and another guy is calling getInstnace so what will happen then ? well lets see Scheduler life and how it serve the threads.

Thread1:hello Mr.Scheduler !

Scheduler: hello thread1 how are you ?

Thread1:never been better( am the one who is going to be executed now yepiiii) and you ?

Scheduler:am fine thx, so are you ready for being executed ?

Thread1:yup i was born ready.

Scheduler:ok go ahead

...5 MilliSeconds

Scheduler:opps sorry i will have to suspend you now Thread1 .

Thread1:oh why :( i didnt finish i am still inside the if checking for the null and myclass is null so
i need just to create the object give me more time plzzzz.

Scheduler: come on be a good thread and leave space for others i promise i will give u another
chance till u r done

Thread2:hello hello my turn , my turn, my turn.

Scheduler:ok ok go ahead

Thread2: ok great am done create the myclass and i have returned a new object from myclass hehe thx Mr.Scheduler

Scheduler:you are welcome , Thread 1 you can resume your work.

Thread1:great thx, so now i will just create an object from myclass ( as it was null object last time i checked so i wont check it anymore), ok great am done and i have a my class object

Scheduler:great have a nice day thread :).


as we can see here that both threads , thread 1 and thread 2 have 2 different objects from myClass which destroy the singleton concept. so how can we overcome this ???


The Solution:

what if we initialized our object as a static initialization instead of checking if it is null or no ? but this way we are sure 100% that it iwll be initialized when our class is loaded by the VM, mmm ok let me show you and example:

public class myClass
{
private static final myClass myclass =new myClass()

pirivate myClass()
{
}

public static myClass getInstance()
{
return myclass ;
}
}

by this way we ensure that only one object will be created once the class is loaded and we wont have any problem if multiple thread called getInstance at the same time

Singleton and Serialization:


so if we made the Singleton class serializable through implementing serializable interface that wont do us any good coz this doesn’t guarantee that it will be single unique object (as each deserialization will result in a new instance from our class) so what we need is to provide the method named readResolve() so now we can write our code like this :
private Object readResolve() throws ObjectStreamException
{return myclass;}
so now we guarantee that only one unique instance will be returned.


Read more!