Saturday, 15 March 2014

Dynamic select box with servlet , Ajax and hashmap result

Ajax


Ajax is an acronym  for Asynchronous Java Script and XML. Ajax is used to easily exchange data between servers and client side UI. Also it has the ability to update part of the page without submitting/ refreshing the pages.

In this tutorial, will see little advanced example, Ajax call using servlet and process the hashmap result.

Application Overview:



  • Create a web page using html

  • Create a select element

  • load the select element value from the Servlet and process the hashmap result


Servlet Code


The servlet process the request and send the data as per the category received. The class com.google.gson.Gson class converts the hashmap object to json string.

AjaxServlet.java
package ajax;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;

/**
* @author Sivaranjani D
*
*/
public class AjaxServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter po = response.getWriter();
String category = request.getParameter("category");

HashMap<String,String> foodList = new HashMap<String,String>();
if(category!=null && category.equalsIgnoreCase("Fruits")){
foodList.clear();
foodList.put("fruits1", "Apple");
foodList.put("fruits2", "Banana");
}else if(category!=null && category.equalsIgnoreCase("Vegetables")){
foodList.clear();
foodList.put("vegetables1", "Brinjal");
foodList.put("vegetables2", "Tomato");
}else{
foodList.clear();
foodList.put("no", "No category selected");
}
po.write(cerateJSON(foodList));

}
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}

private String cerateJSON(HashMap<String, String> lessonList) {
Gson gson = new Gson();
String json = gson.toJson(lessonList);
return json;

}
}

HTML


There are totally two select boxes in this html page. The first one has the static list of categories like fruits and vegetables. The second select box loads vegetables/fruits based on the category selected.

[caption id="attachment_501" align="aligncenter" width="988"]ajaxhashmap ajaxhashmap[/caption]

ajaxservletwithobject.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Ajax With Servlet</title>
<script type="text/javascript" src="js/prototype.js"></script>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui.min-1.10.2.js"></script>
<script language="javascript" type="text/javascript">
    function loadsValuesFromServlet(category) {

        var url = '/Ajax2/loadFromServlet?category=' + category;
        var myAjax = new Ajax.Request(url, {
            method : 'post',
            onComplete : function(originalRequest) {
                var result = originalRequest.responseText.evalJSON();
                ;
                var $this = $('#foodItems');
                $this.empty();
                for ( var key in result) {
                    if (result.hasOwnProperty(key)) {
                        $this.append('<option value='+key+'>' + result[key]
                                + '</option>');
                    }
                }

            }

        });
    }
</script>
</head>
<body>
    <table>
        <tr>
            <td>Select Category</td>
            <td><select name='category' id="category"
                onchange="loadsValuesFromServlet(this.value)">
                    <option value='-1'>--Please Select--</option>
                    <option value='Fruits'>Fruits</option>
                    <option value='Vegetables'>Vegetables</option>
            </select></td>
        </tr>
        <tr>
            <td>Values loded from servlet:</td>
            <td>
                <div id='loadedData'>
                    <select name='foodItems' id="foodItems">
                        <option value='-1'>--Please Select--</option>
                    </select>
                </div>
            </td>
        </tr>
    </table>

</body>
</html>

Download full Application

Result
[caption id="attachment_517" align="aligncenter" width="770"]Ajax Servlet Ajax Servlet[/caption]

Friday, 7 March 2014

Will main thread waits for all it's child threads to complete?

There is lots of confusion whether main thread waits for all it's child threads to complete or not?. Generally there is no child thread concept, here it means the threads which are started in the main block.

Already we have discussed it here about Daemon threads and non-daemon threads and main thread will be a non-daemon thread always. Also threads created by main threads also will be a non-daemon threads until explicitly set.  And JVM waits for all the non-daemon threads to complete.

So comes to our question, will main thread waits for all it's child threads to complete?
I would like to explain it with the below example.
Example
package thread;
/**
* @author Sivaranjani D
*
*/
public class IsMainThreadAlive {

public static void main(String[] args) {
Thread mainThread = Thread.currentThread();
System.out.println("Current thread is "+mainThread.getName());
Runnable target = new targetCode(mainThread, "Thread1");
Thread t1 = new Thread(target);
t1.start();
System.out.println("Thread "+mainThread.getName()+" is alive in main method? "+ mainThread.isAlive());
}

}

class targetCode implements Runnable{
Thread mainThread;
Thread name;
public targetCode(Thread mainThread,String Name){
this.mainThread = mainThread;
this.name=name;
}

public void run() {

for(int i=0;i<50;i++){
System.out.println(Thread.currentThread().getName()+" is executing : "+i);
}

System.out.println("Thread "+mainThread.getName()+" is alive at the end of child thread? "+ mainThread.isAlive());
}

}

output
Current thread is main
Thread main is alive in main method? true
Thread-0 is executing : 0
Thread-0 is executing : 1
Thread-0 is executing : 2
Thread-0 is executing : 3
Thread-0 is executing : 4
Thread-0 is executing : 5
Thread-0 is executing : 6
Thread-0 is executing : 7
.
.
.
.
.
.
Thread-0 is executing : 43
Thread-0 is executing : 44
Thread-0 is executing : 45
Thread-0 is executing : 46
Thread-0 is executing : 47
Thread-0 is executing : 48
Thread-0 is executing : 49
Thread main is alive at the end of child thread? false

Code Explanation

  1. When the main method starts, the main thread starts. So we are getting the current thread and storing it in the variable mainThread.

  2. when we print the stored thread's name it shows "main". This step is to ensure that we have stored the main thread in the variable mainThread.

  3. Creating the runnable object by passing the main thread and that way we are passing the main threads reference to the runnable object.

  4. In run method we are setting some loop to print the values and at the end we are checking whether main thread is alive or not

  5. We have created a thread and passed the runnable object.

  6. we are checking the main thread is alive or not at the end of the main method.


Conclusion:
So from the output, we can see that, the main thread is not running at the end of the child thread because calling isAlive() is false at the end of the child thread.

Thursday, 6 March 2014

Thread - sleep , yield , join with examples

Sleep() method:


Sleep is a static method of the Thread class. That means you can’t stop the thread by it’s instance. Calling the sleep method puts the current thread into sleep mode.
The sleep() method slows down the thread and moves it into sleep. Thread won’t be in either running/ runnable state.
Once it wakes up it goes to runnable state.
Guarantees to stop the current running thread for the specified milliseconds but again no guarantee for the order of execution.
Syntax:

try {
Thread.sleep(5*60*1000); // Sleep for 5 minutes
} catch (InterruptedException ex) { }

Calculator Example
package thread;
/**
* @author Sivaranjani D
*/
public class SleepMethod {
public static int total;
public static void main(String[] args) {CalculateSum calculator = new CalculateSum();
calculator.start();
/**
* Turn this sleep on and off to see the usefulness of sleep method
*/
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("The sum of first 100 Numbers : "+total);
}}
class CalculateSum extends Thread{
@Override
public void run() {
for(int i=0;i<100;i++){
SleepMethod.total=SleepMethod.total+i;
}}}

Output: The sum of first 100 Numbers : 4950

yield() method


Yield() method is closely related with thread priorities. So first will see what is priorities in thread.
Thread priorities
Threads usually run with some priorities usually from 1-10 (Some JVM’s use lesser than 10 also)
Most JVM’s schedule the thread based on thread priorities. But again keep in mind that we can't control the order of thread execution.
In java thread priority can be set by,

Thread thread = new Thread();
thread.setPriority(6);
thread.start();


Also Thread provides the following three static final fields

  • Thread.MIN_PRIORITY (1)

  • Thread.NORM_PRIORITY (5)

  • Thread.MAX_PRIORITY (10)


Why yield is required?
As we know nothing is guaranteed why need to use yield?
This just a hint to the Processor that current thread is willing to give up it’s CPU usage. If there are lot's over CPU utilizing threads, this method will help them to share the time between the threads and thus increases the overall performance of the application.
Summary

  • Thread.yield() is a static method like sleep method.

  • In the priority based scheduling if many threads are with the same priority, then other same priority threads will not get a chance to executes until the current thread finishes.

  • yiled is used for turn taking between equal priority and heavy CPU utilizing threads.


Join () method


join() method is a non-static method.The currently running thread will be joined at the end of the thread instance referenced by this method.
For example, Consider ThreadA is currently in running state. Calling the below code,
ThreadB thread=new ThreadB();
thread.start();
thread.join();

Moves ThreadA to runnable state and makes threadA to wait untill ThreadB completes.

[caption id="attachment_488" align="aligncenter" width="770"]thread join thread join[/caption]

Monday, 3 March 2014

Thread States, Transitions and Scheduler

Thread States and Transitions


Thread has the following five states.

  1. New

  2. Runnable

  3. Running

  4. Waiting/blocking/sleeping

  5. Dead


New – This is the state where the thread is created either by extending the thread class or by implementing the runnable interface. But the start method is not called on the thread. At this stage is thread is not live.
Runnable – When start method is called on a thread, it comes to runnable state and it is called as alive at this stage. But still the actual thread of execution is not started until the thread scheduler selects it. Thread also comes to runnable state after coming back from blocked, waiting or sleeping state.
Running – This is the state where the threads are selected from the runnable pool. At this time, threads are in execution. Threads may go to runnable from this state, when it enter inside blocked, waiting or sleeping.

[caption id="attachment_481" align="aligncenter" width="770"]Thread states and transitions Thread states and transitions[/caption]

Waiting/blocking/sleeping: Thread is alive but not eligible to run. Once the event occurs, it goes to runnable and again it waits for the thread scheduler to select.
Dead: A thread is set to be dead when it completes the run method. It is still a thread object, but not anymore the thread of execution

Thread Scheduler:
The thread scheduler is the part of the JVM that decides which thread should run at any given moment, and also takes threads out of the run state. Assuming In a single processor single core machine there will be only one thread running all the time. So the thread scheduler decides which thread to run.Any thread in runnable pool can be selected by thread scheduler for run. The order of selecting the runnable thread are not guaranteed. It is the scheduler which decides on this. That’s why it is called runnable pool rather than runnable queue.

Influencing thread scheduler
There is no way to control the thread scheduler but there are ways to influences. Thread provides some method for that,
Methods from the java.lang.Thread Class

  • public static void sleep(long millis) throws InterruptedException -

  • public static void yield()

  • public final void join() throws InterruptedException

  • public final void setPriority(int newPriority)


Methods from the java.lang.Object Class

  • public final void wait() throws InterruptedException

  • public final void notify()

  • public final void notifyAll()