Thursday, November 6, 2014

Singleton Design Pattern

The Singleton design pattern is simple and easy to understand. This pattern will ensure that only one object of a particular class is created in virtual machine. In terms of practical usage

 01).Logging 
 02).Caches 
 03).Thread pool, 
 04).Configuration Settings 
 05).Device driver objects 

 lets have a look on the very basic lazy initialization methodology of Singleton  pattern. We can test the Singleton class using following SingletonTest Class When you run the SingltonTest class the result would display as following 

Instance 1 ID :2018699554 
Instance 2 ID :2018699554 
BUILD SUCCESSFUL (total time: 1 second) 

It is very important to see the multi threading behavior on the Singleton design pattern.So lets modify the code, Create two separate classes for use the singleton instance within a thread and test the implementation within the multiple thread environment.


So, what would be the output,

Instance 1 ID :2068989547
Instance 1 ID :1793542001
BUILD SUCCESSFUL (total time: 1 second)

It is clear that the above implementation is not thread safe. There are two different Singleton instances were created in the heap. We need to have a way to overcome this situation.

It is not that hard, Simple this is where the synchronized key word is used. Lets modify the getInstance method in Singleton class. So, what would be the output, Lets see...

Instance 1 ID :1612655617
Instance 1 ID :1612655617
BUILD SUCCESSFUL (total time: 1 second)

Now we are safe. Same instance is used within the multi-threaded environment.
It is really worth to use the Singleton design pattern with the thread safe way prevent multiple instantiations. 
 

Thursday, August 7, 2014

How to get the current location using location manager android

Hi, I developed the Jogging Pal android app and used the following logic to get the current location using network and gps. I created a separate class as a service extended from Service abstract class and implemented it from LocationListner interface. It is better to check the provider status before you get the location unless it will give an exception. Configure the min distance change for update and min time change for update as you wish. Pass theses parameters to location manager's requestLocationUpdates method. For retrieving the current location you can use the getLastKnownLocation method in location manager passing the particular provider. This will give you the current location. When you are using this for indoor activities the results will not be too accurate. And finally make sure that you have added the permission on the Manifest, Jogging Pal / Android