I am a Developer, Blogger and Coffee addict. Java developer by profession, Q2A developer by addiction. This is my personal website where I write few stuff which could be useful for other developers.
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 collected.
packagecom.amiyasahu;publicclassSingleton{privateSingleton(){// Private constructor}privatestaticThreadLocal<Singleton>_threadLocal=newThreadLocal<Singleton>(){@OverrideprotectedSingletoninitialValue(){returnnewSingleton();}};/**
* Returns the thread local singleton instance
*/publicstaticSingletongetInstance(){return_threadLocal.get();}}
If you are using java8 or above, you can replace the _threadLocal definition with below.
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.
packagecom.amiyasahu;importjava.util.Random;publicclassThreadLocalTestextendsThread{publicvoidrun(){Singletoninstance1=Singleton.getInstance();System.out.println(getThreadName()+instance1);sleep(100,50);// sleep for some timeSingletoninstance2=Singleton.getInstance();System.out.println(getThreadName()+instance2);booleanequal=instance1==instance2;Stringmessage=equal?"Both are equal":"Not equal";System.out.println(getThreadName()+message);}privatevoidsleep(intmax,intmin){try{inttime=newRandom().nextInt(max-min+1)+min;Thread.sleep(time);}catch(InterruptedExceptione){e.printStackTrace();}}privateStringgetThreadName(){return"["+Thread.currentThread().getName()+"] - ";}}
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.
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});}});});
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.
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
<inputtype="checkbox"id="select-all"/> Select All
<inputtype="checkbox"class="checkbox"name="chk[]"value="1"> 1
<inputtype="checkbox"class="checkbox"name="chk[]"value="2"> 2
<inputtype="checkbox"class="checkbox"name="chk[]"value="3"> 3
2. JQuery code
$(document).ready(function(){$('#select-all').click(function(event){varbtn=this,toStatus=btn.checked;//loop through each checkbox$('.checkbox').each(function(){$(this).prop('checked',toStatus);});});});
vara=10,b=20;console.log("a = "+a+" , b = "+b);// a = 10 , b = 20b=[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
When you make a AJAX call to the server using JQuery, it adds a special header along with the request.
So you can check on the server side against this header.
If the header HTTP_X_REQUESTED_WITH is present and is equal to XMLHttpRequest, then the AJAX call is made via jQuery.
<?php// returns true if the request is made with XMLHttpRequest header functionisXhr(){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 ";}