More about Singleton Design Pattern

In our previous article about Singleton Design Pattern, we have discussed about basics of its working and design. Today we are adding more points to it.

While implementing singleton, we need to take care that it should work well in multiple thread environment. So one option is to initialize the instance eagerly at the time of declaring the variable. But if we want to initialize the variable lazily, i.e. only when it is required, then we can make the method 'getSharedInstance' synchronized. But that will slow down the operations in every request. But we need synchronization only if instance is null and we need to create it.

So one approach could be to use double 'null' check as given below:

getSharedInstance()
{
// first check to make sure that synchronization comes in effect only if instance is null
 if (instance == null )
 {
  // synchronizing to avoid access my multiple threads
  synchronized (this)
  {
   // check again if instance is not null, as first check of not null may be passed by more than one thread
   if (instance == null)
   {
    instance = new Instance();
   }
  }
 }
 return instance;
}

But in above approach, we are still synchronizing a code block, and checking the instance for 'null' twice. There can be another better approach as given below: 

public class SingletonObject 
{
  public static SingletonObject getSharedInstance ()
 {
   return SingletonHolder.sharedInstance;
 }

 private static class SingletonHolder 
{
 static SingletonObject sharedInstance = new SingletonObject();
}
}

Here no synchronization is required in code. The instance will be initialized lazily only when request will hit getSharedInstance method for the first time, as inner static class will be initialized then.

With these approaches, you need to take care of few points like
  • Cloning should not be supported
  • Constructor of class should be private
  • Serialization should be controlled, i.e. we should override readResolve method to return the shared instance.

But later 'Joshua Bloch' has proposed another approach, termed as best approach for implementing Singleton Patter. This is to use 'enum' for implementation. Example is given below:

// Enum Singleton
public enum SingletonObject
{
  SHAREDINSTANCE;

  public void someMethod()
  {
    .....
  }
}

And it is done. Now you can use it like

SingletonObject.SHAREDINSTANCE.someMethod()

It is perfectly thread safe without any double check for null or synchronization. Check in serialization methods are also not required, because Enum are serialization specially in Java by just writing their names in stream.

With this approach, there is no chance to have more than one instance of object with any of the hook. From Joshua book - 
This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.

Solution for 'NullPointerException' on Eclipse Startup

We faced a scenario where we abruptly had to kill the java while eclipse was running on system. However, when we tried to run the Eclipse again, it just get hanged and console/logs exposed us following error:

[weblogic@localhost oepe-indigo-12.1.1.0.1]$ /home/weblogic/Programs/Oracle/oepe-indigo-12.1.1.0.1/eclipse -vm /usr/java/jdk1.6.0_33/bin
LogFilter.isLoggable threw a non-fatal unchecked exception as follows:
java.lang.NullPointerException
at org.eclipse.core.internal.runtime.Log.isLoggable(Log.java:101)
org.eclipse.equinox.log.internal.ExtendedLogReaderServiceFactory.safeIsLoggable(ExtendedLogReaderServiceFactory.java:59)
org.eclipse.equinox.log.internal.ExtendedLogReaderServiceFactory.logPrivileged(ExtendedLogReaderServiceFactory.java:164)
org.eclipse.equinox.log.internal.ExtendedLogReaderServiceFactory.log(ExtendedLogReaderServiceFactory.java:150)
org.eclipse.equinox.log.internal.ExtendedLogServiceFactory.log(ExtendedLogServiceFactory.java:65)
org.eclipse.equinox.log.internal.ExtendedLogServiceImpl.log(ExtendedLogServiceImpl.java:87)
org.eclipse.equinox.log.internal.LoggerImpl.log(LoggerImpl.java:54)
org.eclipse.core.internal.runtime.Log.log(Log.java:60)
org.tigris.subversion.clientadapter.javahl.Activator.isAvailable(Activator.java:92)
org.tigris.subversion.clientadapter.Activator.getClientAdapter(Activator.java:67)
org.tigris.subversion.subclipse.core.SVNClientManager.getAdapter(SVNClientManager.java:127)
org.tigris.subversion.subclipse.core.SVNClientManager.getSVNClient(SVNClientManager.java:94)
org.tigris.subversion.subclipse.core.SVNProviderPlugin.getSVNClient(SVNProviderPlugin.java:462)
org.tigris.subversion.subclipse.core.status.RecursiveStatusUpdateStrategy.statusesToUpdate(RecursiveStatusUpdateStrategy.java:62)
org.tigris.subversion.subclipse.core.status.StatusCacheManager.refreshStatus(StatusCacheManager.java:270)
org.tigris.subversion.subclipse.core.resourcesListeners.FileModificationManager.refreshStatus(FileModificationManager.java:220)
org.tigris.subversion.subclipse.core.resourcesListeners.FileModificationManager.resourceChanged(FileModificationManager.java:161)
org.eclipse.core.internal.events.NotificationManager$1.run(NotificationManager.java:291)
org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
org.eclipse.core.internal.events.NotificationManager.notify(NotificationManager.java:285)
org.eclipse.core.internal.events.NotificationManager.broadcastChanges(NotificationManager.java:149)
org.eclipse.core.internal.resources.Workspace.broadcastPostChange(Workspace.java:395)
org.eclipse.core.internal.resources.Workspace.endOperation(Workspace.java:1530)
org.eclipse.core.internal.resources.InternalWorkspaceJob.run(InternalWorkspaceJob.java:45)
org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)

And the solution we found was, it happens because some of the metadata file got corrupted during abrupt exit. So we follows the steps mentioned below to get eclipse started again:
  1. cd .metadata/.plugins
  2. mv org.eclipse.core.resources org.eclipse.core.resources.bak
  3. Start eclipse
  4. It will start but will show errors with opened tabs. This is because we have changed the resources folder, which eclipse use for managing the resources
  5. Close all opened tabs
  6. Exit from Eclipse
  7. Delete any newly create org.eclipse.core.resources folder
  8. Rename back the 'org.eclipse.core.resources.bak' to 'org.eclipse.core.resources'
  9. Start Eclipse
  10. It should start fine with all projects
 Hopefully you won't face any problem further, but will depend on scenario. Please share your experience if that was different.

Vedic Math - Squaring numbers near base

Note: Vedic Math Blog has been moved to http://vedicmath.vedantatree.com/. Please bookmark the new address for new and existing blogs.

In the previous article, we have discussed about the method of multiplication by using the base value. In this article, we shall learn the squaring of numbers by using base value. Squaring numbers near base is much easier as there is no possibility of different cases that we discussed earlier for multiplication, like
1. One number is above the base and the other number is below it
2. Numbers near different bases like multiplier is near to different base and multiplicand is near to different base.

So it is comparatively simpler. Here, we can use the sub sutra “whatever the extent of its deficiency, lessen it still further to that extent; and also set up the square of that deficiency”.

In this, first corollary is “All from 9 and the last from 10”. This method will work for any type of squaring. There is another method by taking the sutra "Vertically and Crosswise" but that we will discuss later.

Suppose we have to find the square of 8. The following will be the steps for it:
1. We shall take the nearest power of 10 (10 itself in this case) as our base.
2. 8 is '2' lesser than 10, so we shall decrease 2 from 8 (i.e. 8 - 2 = 6). This will become the left side of answer.
3. And, for right part of answer, we write down the square of that deficiency i.e. 2 x 2 = 4
4. Thus 8 x 8 = 64

In exactly the same manner, we say
72 = (7-3)  |  32
     =  4  |  9
     =  49

92 = (9-1)  |  12
     =  8  |  1
     =  81

62 = (6-4)  |  42
     =  2     |     6                (Here, since right side is 2 digit number, so '1' will be carried to its left)
                   1
     =  3     |   6        
     =  36