Amiya Sahu Web Developer

How to create singleton instance per thread in java

In case you are new to the term singleton design pattern, It is recommended that, you read this article before proceeding further.

By this time I assume you know the basics and usefulness of a singleton design pattern.

Sometimes we endup in a situation where we can not use the singleton classes in a multiple threaded application. This could be for sevaral reasons like, making use of some data or some instance which are not thread-safe (eg. HashMap).

To create singleton instance per thread, we can make use of a ThreadLocal instance (java doc).

When we invoke get() on a ThreadLocal instance, it returns an independently initialized copy of the variable for each thread. ThreadLocal instances are typically private static fields in classes which we wish to make singleton per thread.

Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are garbage colelcted.

Example 1 - By using static reference of ThreadLocal

package com.amiyasahu;

public class Singleton {

    /**
     * Private constructor
     */
    private Singleton() {

    }

    private static ThreadLocal<Singleton> _threadLocal = 
                new ThreadLocal<Singleton>() {
                    @Override
                    protected Singleton initialValue() {
                        return new Singleton();
                    }
                };

    /**
     * Returns the thread local singleton instance
     * 
     * @return
     */
    public static Singleton getInstance() {
        return _threadLocal.get();
    }
}

Now lets create the test method. Here we will print the instance hashcode with the thread name, so that we can conclude which instance is bound for a thread.

package com.amiyasahu;

import java.util.Random;

public class ThreadLocalTest extends Thread {

    public void run() {
        Singleton instance1 = Singleton.getInstance();
        System.out.println(getThreadName() + instance1);
        sleep(100, 50); // sleep for some time
        Singleton instance2 = Singleton.getInstance();
        System.out.println(getThreadName() + instance2);
        boolean equal = instance1 == instance2;
        String message = equal ? "Both are equal" : "Not equal";
        System.out.println(getThreadName() + message);
    }

    private void sleep(int max, int min) {
        try {
            int time = new Random().nextInt(max - min + 1) + min;
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private String getThreadName() {
        return "[" + Thread.currentThread().getName() + "] - ";
    }

}

Run the test case -

package com.amiyasahu;

public class App {
    public static void main(String[] args) {
        Thread t1 = new ThreadLocalTest();
        t1.start();
        
        Thread t2 = new ThreadLocalTest();
        t2.start();
        
        Thread t3 = new ThreadLocalTest();
        t3.start();
    }
}

Output -

[Thread-1] - com.amiyasahu.Singleton@7504f8eb
[Thread-2] - com.amiyasahu.Singleton@274b8c21
[Thread-0] - com.amiyasahu.Singleton@50dcdeae
[Thread-1] - com.amiyasahu.Singleton@7504f8eb
[Thread-1] - Both are equal
[Thread-0] - com.amiyasahu.Singleton@50dcdeae
[Thread-0] - Both are equal
[Thread-2] - com.amiyasahu.Singleton@274b8c21
[Thread-2] - Both are equal

This clearly shows, it is creating a unique instance per thread.

Example 2 - By using generic factory pattern

Step 1 : Create the singleton class

package com.amiyasahu.factory;

public class Singleton {

}

Step 2 : Create the interface

package com.amiyasahu.factory;

public interface Factory<T> {
    public T create();
}

Step 3 : Create the generic ThreadLocalFactory utility class

Now create the generic ThreadLocalFactory which can convert any Factory to a ThreadLocal scope.

package com.amiyasahu.factory;

public class ThreadLocalFactory<T> implements Factory<T> {

    private final ThreadLocal<T> _threadLocal;

    public ThreadLocalFactory(final Factory<T> factory) {
        _threadLocal = new ThreadLocal<T>() {
            @Override
            protected T initialValue() {
                return factory.create();
            }
        };
    }

    @Override
    public T create() {
        return _threadLocal.get();
    }
}

Step 4 : Create a singleton factory

package com.amiyasahu.factory;

public class SingletonFactory implements Factory<Singleton> {
    @Override
    public Singleton create() {
        return new Singleton();
    }
}

Step 4 : Push the singleton factory to the thread local scope

package com.amiyasahu.factory;

public class ThreadLocalSF {

    private static Factory<Singleton> factory = null;

    public static Singleton getInstance() {

        if (factory == null) {
            SingletonFactory sf = new SingletonFactory();
            factory = new ThreadLocalFactory<>(sf);
        }
        
        return factory.create();
    }

}

We are done. Now we have created a Thread local singleton factory, which will return unique instance per thread.

Lets write the test method now.

package com.amiyasahu.factory;

import java.util.Random;

public class ThreadLocalTest extends Thread {

    public void run() {
        Singleton instance1 = ThreadLocalSF.getInstance();
        System.out.println(getThreadName() + instance1);
        sleep(100, 50); // sleep for some time
        Singleton instance2 = ThreadLocalSF.getInstance();
        System.out.println(getThreadName() + instance2);
        boolean equal = instance1 == instance2;
        String message = equal ? "Both are equal" : "Not equal";
        System.out.println(getThreadName() + message);
    }

    private void sleep(int max, int min) {
        try {
            int time = new Random().nextInt(max - min + 1) + min;
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private String getThreadName() {
        return "[" + Thread.currentThread().getName() + "] - ";
    }

}

Now lets run the test method -

package com.amiyasahu;

import com.amiyasahu.factory.ThreadLocalTest;

public class App {
    public static void main(String[] args) {
        Thread t1 = new ThreadLocalTest();
        t1.start();
        
        Thread t2 = new ThreadLocalTest();
        t2.start();
        
        Thread t3 = new ThreadLocalTest();
        t3.start();
    }
}

Output -

[Thread-0] - com.amiyasahu.factory.Singleton@4afbf04a
[Thread-1] - com.amiyasahu.factory.Singleton@13f6c937
[Thread-2] - com.amiyasahu.factory.Singleton@5b8425b7
[Thread-1] - com.amiyasahu.factory.Singleton@13f6c937
[Thread-1] - Both are equal
[Thread-0] - com.amiyasahu.factory.Singleton@4afbf04a
[Thread-0] - Both are equal
[Thread-2] - com.amiyasahu.factory.Singleton@5b8425b7
[Thread-2] - Both are equal

This clearly demonstrates creation of unique objects per thread.

How to Make a dropdown readonly using Jquery

Dropdown (select element) is always read only. User do not edit it. User can select any of the option of its own chice. Unlike other html elements, it dont have a attribute which can make the element readony and prevent users to change its value.

So how do we do this, when we want to prevent the user not to edit its selected option.

There is a little trick. Why can’t we disable it.

Wait a second…

But as we are disabling this field, the field will not be the part of the request when the form is submitted.

We can do some work around for this.

So we need to use a hidden field to store disabled selected-option value. When the moment select element is disabled we need to create a hidden input field in the form and store the selected value. The moment it is enabled we need to restore the element with the value stored in the hidden field.

Here you go with a code example -

HTML code

<form action="#">
    <select id="choose" name="alpha">
        <option value="A">A</option>
        <option value="B">B</option>
        <option value="C">C</option>
    </select>
</form>

<button id="toggle">toggle enable/disable</button>

JQuery code

jQuery(document).ready(function($) {
    var $select = $('#choose'), 
    name = $select.prop('name'), 
    $form = $select.parent('form');

    //store the name in the data attribute 
    $select.data('original-name', name);  

    $('#toggle').on('click', function(event) {
        if($select.prop('disabled')){
            //enable the element
            //remove the hidden fields if any
            $form.find('input[type="hidden"][name='+name+']')
                 .remove(); 
            //restore the name and enable 
            $select.prop({ name : name, 
            		disabled : false}); 
        } else {
            //disable it 
            var $hiddenInput = $('<input/>', { type  : 'hidden',
                    	name  : name, 
                    	value : $select.val()
                    });

            //append the hidden field to the form
            $form.append( $hiddenInput );  
            //change name and disbale 
            $select.prop({ name : name + "_1", disabled : true });
        }
    });
});

Here is a live example.

How to count number of key/value pairs in JSON Object

To count the number key/value pairs in a JSON object we need to convert an array. And then we can easily count the number of element in the array which is same as the number key value pairs in the json object.

Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found in the object.

function countObjectKeys(obj) { 
    return Object.keys(obj).length; 
}

//Usage 
var emp = {"firstName":"John", "lastName":"Doe"};
console.log(countObjectKeys(emp)); //2

Toggle Checkboxes using JQuery ( Select All/Select None )

When user clicks Select All checkbox, the code first checks the status of checkbox with id select-all, and loops though each checkbox with class checkbox update their checked property to true. When it is clicked again then it will update their checked property to false.

1. HTML Code

<input type="checkbox" id="select-all"/> Select All
<input type="checkbox" class="checkbox" name="chk[]" value="1"> 1
<input type="checkbox" class="checkbox" name="chk[]" value="2"> 2
<input type="checkbox" class="checkbox" name="chk[]" value="3"> 3

2. JQuery code

$(document).ready(function() {
    $('#select-all').click(function(event) {
    	var btn = this, toStatus = btn.checked;
    	//loop through each checkbox
        $('.checkbox').each(function() { 
            $(this).prop('checked', toStatus);
        });
    });
});

Here is the live exaample

How to create nested HTML elements in JQuery

JQuery code

var $elem = $('body div.main');
$elem.append(
            $('<div/>', {'class': 'wrapper'}).append(
                $('<div/>', {'class': 'inner'}).append(
                    $('<span/>', {text: 'Some text'})
                )
            ).append(
                $('<div/>', {'class': 'inner'}).append(
                    $('<span/>', {text: 'Other text'})
                )
            )
        );

Result

<div class="main">
	<div class="wrapper">
		<div class="inner">
			<span>Some text</span>
		</div>
		<div class="inner">
			<span>Other text</span>
		</div>
	</div>
</div>

Here is a live example

Intresting Javascript tricks

Swap variables

var a = 10 , b = 20 ; 
console.log("a = " + a + " , b = " + b);  // a = 10 , b = 20
b = [a, a = b][0];                        // swap the variables 
console.log("a = " + a + " , b = " + b);  // a = 20 , b = 10

Truncate a value to a Integer in Javascript

Usage Result
~~0.125 0
~~1 1
~~1.6 1
~~"2.59" 2
~~-2.8 -2
~~"Apple" 0
~~[] 0
~~null 0

Note -: It never returns NaN. If it fails, it just returns 0

Check if given input is numeric in Javascript

function isNumeric (arg) {
    return !isNaN(parseFloat(arg)) && isFinite(arg);
}
Usage Result
isNumeric(10) true
isNumeric(10.234) true
isNumeric(0.215) true
isNumeric('10') true
isNumeric('10.234') true
isNumeric('0.215') true
isNumeric('') false
isNumeric('Qwerty') false
isNumeric('43Agd') false

Detect JQuery AJAX Requests with PHP

<?php
// returns true if the request is made with XMLHttpRequest header 
function isXhr() {
    return $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
}

//Usage 
if( isXhr() ) {
    echo "The AJAX Request is made from JQuery ";
} else {
    echo "The AJAX Request might not be made from JQuery ";
}

How to delete a remote tag in git

If you need to delete a remote tag named – oldtag use the below command

git tag -d oldtag
git push origin :refs/tags/oldtag

How to check if an element exists in an array in Javascript

The below function can efficiently check whether an element exists in the array or not

if (!Array.prototype.elemetExists) {
    Array.prototype.elemetExists = function (string) {
        return !!~this.indexOf(string);
    };
}

//usage 
var fruits = ['Apple' , 'Banana' , 'Orange' , 'Mango'];
console.log(fruits.elemetExists('Banana'));  //true 
console.log(fruits.elemetExists('Lichi'));  //false

How to Destroy CKEditor in small screen devices

The CKeditor fires an event instanceReady once the instances are ready to be used.

So we need to create a listener which will listen for this event.

We will only execute the event handler if the browser window width is less than the some defined width for a small screen devices.

In Jquery the width of the browser window can be determined by $.width() method by calling on window object.

<script type="text/javascript">
$(document).ready(function() {
    function destroyCKEditor(minWidth) {
        if (typeof CKEDITOR != 'undefined' 
            && $( window ).width() < minWidth) {
            CKEDITOR.on("instanceReady", function(event)
            {
               $.each(CKEDITOR.instances, function(index, instance) {
                    instance.destroy();
               });
            });
        };
    }
    //usage 
    //destroy ck editor in devices less than 768px wide 
    destroyCKEditor(768);
});
</script>

How to use this for Question2Answer websites

If you are a owner of a Question2Answer website and you wish to show the plain text editor to your users who is viewing the site on their mobile device, this would be the best way to go.

Steps –

  1. Login into your website as Admin
  2. Navigate to Admin -> Layout
  3. Paste the above code in Custom HTML at bottom of every page: section
  4. You may change the value here given as per your requirement destroyCKEditor(500);. Here the 500 is the minimum allowed width, below which all the CKEditor instances will be destroyed