Digesting Singleton Design Pattern in Java

Design Patterns are very popular among software developers. A design pattern is a well-described solution to a common software problem. The Singleton is one of the Creational Design Patterns in Java.

What is the purpose of Singleton?

The purpose of the singleton class is to control object creation, limiting the number of objects to only one. The singleton allows only one entry point to create the new instance of the class.

Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons are often useful where we have to control the resources, such as database connections or sockets.

It seems to be a very simple design pattern but when it comes to implementation, it comes with a lot of implementation concerns. The implementation of Singleton pattern has always been a controversial topic among developers. Here, we are going to discuss how to create a Singleton class that fulfills its purpose :

Restrict the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine.

Let’s create Singleton class in java and test it in different conditions.


Create Singleton class in Java:

To implement the singleton class, the simplest way is to make the constructor of the class as private.

  1. Eager initialization:

In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a singleton class.

By making the constructor as private we are not allowing other class to create a new instance of the class we want to create the singleton. Instead, we are creating one public static method (commonly name as for getInstance()) to provide the single entry point to create the new instance of the class.

This approach has one drawback. Here instance is created even though client application might not be using it. This might be a considerable issue if your singleton class in creating a database connection or creating a socket. This may cause the memory leak problem. The solution is to create the new instance of the class, when needed. This can be achieved by Lazy Initialization method.

2. Lazy initialization:

Opposite to Eager initialization, here we are going to initialize new instance of the class in getInstance() method it self. This method will check if there is any instance of that class is already created? If yes, then our method (getInstance()) will return that old instance and if not then it creates a new instance of the singleton class in JVM and returns that instance. This approach is called as Lazy initialization.

We all know that in Java if the two objects are same then, their hash key have to be equal. Let’s test that. If the above singleton is correctly implemented than below code should return the same hash key.

Below is the output log with the hash code of both the instances.

0-qifle4zoftvjm3zl

We can see that both the instances are having the same hash code. So, that means above code will make the perfect singleton. Right???? No.


What about Java Reflection API?

In above singleton class, by using reflection we can create more than one instance. Those of you don’t know what is the Java Reflection API is, Java Reflection is a process of examining or modifying the run-time behavior of a class at run time.

We can make the new instance of the singleton class by changing the constructor visibility as public in run-time and create new instance using that constructor. Run the below code and see it our singleton survives?

Here is the output of hash codes of both instances.

0-gi1s0koxigea9pp

Both the instances have a different hash code. That clearly indicates that our singleton class failed this test.

Solution:

To prevent singleton failure while due to reflection we have to throw a run-time exception in constructor, if the constructor is already initialized and some class to initialize it again. Let’s update our SingletonClass.java.


Is our singleton class thread safe?

If two threads try to initialize our singleton class at almost the same time, what happens? Let’s test below code in which two threads are created almost simultaneously and they are calling getInstance().

If you run this code many times, you will see sometimes both the threads creates different instances.

0-gwpokfxamyzr3cr5

That means our singleton class is not Thread safe. Both the threads calls out getInstance() method at the same time, the sSoleInstance == null condition will return for both the thread. So, two different instances of the same class will be created. That will break the singleton principle.

Solution:

1. Make getInstance() synchronized:

Let’s make our getInstance() method synchronized.

As we made our getInstance() class synchronized the second thread will have to wait until the getInstance() method is completed for the first thread. This way we can achieve thread safety. But, there are some cons of using this approach:

  • Slow performance because of locking overhead.
  • Unnecessary synchronization that is not required once the instance variable is initialized.

2. Double check locking method:

We can overcome this issue if we use Double check locking method to create the singleton. In this, we make the singleton class in the synchronized block if the instance is null. So, the synchronized block will be executed only when the sSoleInstance is null and prevent unnecessary synchronization once the instance variable is initialized.

3. Use volatile keyword:

On the surface, this method looks perfect, as you only need to pay price for synchronized block one time, but it still was broken, until you make sSoleInstance variable volatile.

Without volatile modifier, it’s possible for another thread in Java to see half initialized state of _instance variable, but with volatile variable guaranteeing happens-before relationship, all the write will happen on volatile sSoleInstance before any read of sSoleInstance variable.

Now, our singleton class is thread safe. Making singleton thread safe is especially required in multi-threaded application environment like in Android Applications.


Make Singleton safe from Serialization:

Sometimes in distributed systems, we need to implement Serializableinterface in Singleton class. By doing that we can store its state in the file system and retrieve it at later point of time. Let’s test our singleton class whether it maintains single instance after serializable and deserializable operations?

0-qifle4zoftvjm3zl

We can see that the hash code of both the instances are different. That is clearly violates singleton principle. The problem with above serialized singleton class is that whenever we deserialize it, it will create a new instance of the class.

To prevent creation of another instance we have to provide the implementation of readResolve() method. readResolve() replaces the object read from the stream. This ensures that nobody can create another instance by serializing and deserializing the singleton.


Conclusion:

At end of the article, we can make our class a singleton class that is thread and reflection safe. This singleton is still not the perfect singleton. We can violate the singleton principle by creating more than one instance of the singleton class by using cloning or using multiple class loaders. But for the most of the applications, above implementation of singleton will work perfectly.

Advertisements

Keep your device screen on smartly!!!

Ideally, when you user is looking at the screen, your application should prevent the device screen from turning off.

This is the huge deal for the blogging, messaging applications. These applications display textual content to their user. Reading those textual content takes more time to the user. While reading that content (let say an article) if the user does not interact with the display and the screen turns off because of the screen timeout that is frustrating to the user. It will destroy the concentration of the user and breaks the link.

If you are using Samsung devices you might know there is one feature called “Smart Stay”. When this feature is enabled, the device will prevent your screen from turning off regardless of your screen timeout settings. But, this technology is only available on some Samsung devices. What if we want to use that technology in our application to solve above problem? Today, I am going to present the solution of this problem.


Here is the solution:

Prevent-Screen-Off” library handles screen on/off timing smartly. It prevents device display from turning off when the user is looking at the screen and he/she might be reading some textual content provided by your application. As soon as the user stop looking at the screen it will allow phone screen to turn off.

How this works?

  • This library uses the front camera to sense when you are looking at your device
  • This uses Google Play Services Mobile Vision API to track users eye using the device front camera. This uses the same algorithm to detect user’s eyes used in “UserAwareVideoView”. (I wrote a whole article regarding how UserAwareVideoView works. You can find it from here.)
  • It keeps the screen from turning off regardless of the screen timeout setting if the user is looking at the screen by detecting user’s eyes.

Integrating the library in your application:

Let’s dive into some technical stuff and see how you can integrate this library in your application and use it.

Add Gradle dependency:

  • To start with the integration, first provide the Gradle dependency of the library by entering below lines in your module level build.gradle.

This library adds android.permission.CAMERA and android.permission.WAKE_LOCK permission in your applications AndroidManifest.xml file.

Initialize in your activity:

  • First, you need to inherit AnalyserActivity in the activity which you want to control screen on/off automatically. The library will synchronize with your activity life-cycle and start and stop eye tracking based on your activity state.
  • Library will start tracking user eyes as soon as activity comes into the foreground. If the user is looking at the screen this will prevent the screen from turning off.
  • When library detects that the user is not looking at the screen, this will turn off the screen after some time.
  • It will stop eye tracking when your activity goes into the background to preserve the battery.
  • Implement ScreenListener to receive the callbacks from the library.
  • Handle the callbacks and errors received from ScreenListener.
  • That’s it. You successfully integrated the library. By the way, if you want to try our sample application before integration, you can find it from this link.

This library won’t work if,

  • When camera fails to initialize or your front camera is being used by another application. In that case, you will receive Errors.UNDEFINED error code in onErrorOccured event.
  • When the light source is behind the user or there is low light in the surrounding environment, so that eye tracking is not possible. In that case, you will receive Errors.LOW_LIGHT error code in onErrorOccured event. At this point, you can show a message to your user to go to the place where enough light available.
  • Google Play Service not available. In that case, you will receive Errors.PLAY_SERVICE_NOT_AVAILABLE error code in onErrorOccured event. In this case, the library will automatically display the dialog to install or update Google Play Services application from the play store, if the device supports Google Play Service.
  • If the device does not have the front camera. In that case, you will receive Errors.FRONT_CAMERA_NOT_AVAILABLE error code in onErrorOccured event. In this case, we are helpless. 😦

Where can you use this feature?

  • Tracking user’s eye using device camera consumes more battery. So, it is advisable that you don’t integrate automatic screen control in every screen of your application.
  • You can integrate this features in your application activity, which has more textual content to read. An e.g. activity that shows chat conversation in messaging app or activity that displays full article in your blogging application. (This list can be extended for may other use cases. Let me know if you have more ideas in comments.)

For the full sample application and the source code, visit GitHub.

User Aware Video View

These days all new smartphones are packed with lots of sensors and most of the smartphone contains the front (selfie) camera. So, why don’t we make use of them to improve the user experience? While watching the video on your device is the most important feature for many social sharing, messaging and media applications.

UserAwareVideoView is a customized video viewer that smartly play and pause the video based on your user is looking at the video or not. If the user is not looking at the screen then this will automatically pause the video, so your user does not miss any part of the video.

UserAwareVideoView inherits the android framework’s default VideoViewclass. So, it has all the features that video viewer has. More than that it makes it easy to convert your all the default video views to UserAwareVideoView in your existing application.

How does it work?

At its core UserAwareVideoView uses Google Play Service Mobile Vision API for the image processing. It uses front camera of the device to track user’s eyes.

When VideoView.start() is called, it starts the eye tracking algorithm and starts tracking the user’s eyes. It also starts monitoring surrounding light intensity and if the light intensity is not enough for processing camera output, it stops tracking the user’s eyes.

If the user is not looking at the device screen, UserAwareVideoView will pause the video and it will resume the video as soon as the user starts looking at the screen. Pretty amazing huh!!!

Whenever VideoView.stopPlayback() or VideoView.pause() is called, this will UserAwareVideoView will release the camera and stop eye tracking to consume the battery.

How to integrate?

To start with the integration, first provide the Gradle dependency of the library by entering below lines in your module level build.gradle.

 

This library automatically adds android.permission.CAMERA permission in your applications AndroidManifest.xml file.

Add the UserAwareVideoView in you xml layout of your activity or fragment. You can use UserAwareVideoView just like you use the default VideoView in your layout.

Initialize the UserAwareVideoView in your activity/fragment by following three steps:

  • Step-1: Check for the Camera permission in run-time.
  • Step-2: Register UserAwarenessListener to get the callbacks from the UserAwareVideoView whenever error occurs in eyes detection or eye detection starts stops.
  • Step-3: Handle errors that may occur while eyes detection. There are main 4 errors. You can detect those errors by error code. Below is the snippet showing how you can handle different errors.

That’s it. You are ready with UserAwareVideoView.

Conclusion:

By using the UserAwareVideoView, you can make your application smart that responds to the user’s activity and uses the phone’s sensors to control the video playback so that your user don’t miss any part of the video.

For the full sample application and the source code, visit GitHub.