Monday, 4 April 2011

Core Java: Thread Forking

IMPLEMENTING RUNNABLE INTERFACE:

To implement Runnable, we must only implement the method called run( ), which is declared as follows:
public void run( )
Inside this method we have to code that constitute the new thread. It is the entry point for another, concurrent thread of execution within our program. This thread will end when run( ) returns. After declaring a class that implements Runnable interface, we should initiate the object of type Thread using one of its several constructors like:
Thread(Runnable threadOb, String threadName)
In this constructor, threadOb is an instance of a class that implements the Runnable interface. This defines where execution of the thread will begin. The name of the new thread is specified by threadName. After the new thread is created, we have to start the thread using start( ) method of Thread class, as it will not start automatically.

For example the following example illustrate the point:

class NewThread implements Runnable
{
Thread t;
NewThread()
{
t=new Thread(this, "MyThread");
System.out.println(t);
t.start();
}
public void run()
{
// Do sht...
System.out.println(" Exiting from the child thread");
}
}

EXTENDING THREAD CLASS:

The second way to create a thread is to create a new class that extends Thread, and then to create an instance of that class. The extending class must override the run( ) method. Here is the same program as above, rewritten to extend Thread:

class NewThread extends Thread
{
NewThread()
{
super("MyThread");
System.out.println(t);
start();
}
public void run()
{
// Do sht...
System.out.println(" Exiting from child thread");
}
}

N.B. if we are not overriding any of Thread’s other methods, it is probably the best approach simply to implement Runnable interface. Moreover that if the class has already been extended from another class then we have to implement Runnable interface.

Core Java: Thread Inplementation

Java’s multithreading system is built upon the Thread class, its methods, and its companion interface, Runnable. Thread encapsulates a thread of execution. We can not directly refer to the ethereal (n. heavenly) state of a running thread, we should deal with it through its proxy, the thread instance that produced it. To create a new thread our program will either extend Thread or implement the Runnable interface.
To start the execution of a thread, we should call the start( ) method for the Thread object. The code that executes in a new thread is always a method called run( ), which is declared like:public void run( ) . Threads other than the main thread in a program always start in the run( ) method for the object that represents the thread. But here is a problem; we are unable to call run method to start a thread, we should call the start( ) method for the object representing the thread and that causes the run( ) method to be called. When we want to stop the execution of a thread that is running, we should call the stop( ) (now depricated) method for the Thread object. This is because, the threads are always run and managed by operating system and a new thread can only be created and started by the operating system. If we were to call run( ) method ourselves, it would simply operate like any other method, running in the same thread as the program that calls it. When we call the start( ) method for a thread object, we are calling a native code method that causes the operating system to initiate another thread from which the run( ) method for the thread object executes. Hence we should start our thread by calling the start( ) method.

Core Java: Exceptions in Java Thread

When the main thread in a single-threaded application throws an uncaught exception, you are likely to notice because the stack trace is printed on the console (and because the program stops).
By invoking stat() method another thread is started, but the run() method is not really the "main" method of the new thread. The run() method is executed inside a context that allows the virtual machine to handle runtime exceptions thrown from the run() method.
All uncaught exceptions are handled by code outside of the run() method before the thread terminates. The default exception handler is a Java method; it can be overridden. This means that it is possible for a program to write a new default exception handler.
The default exception handler is the uncaughtException() method of the ThreadGroup class. It is called only when an exception is thrown from the run() method. The default implementation of the uncaughtException() method is to print out the stack trace of the Throwable object thrown by the run() method (if it is not an object of ThreadDeath class).


Moreover that the basic Thread Exception classes are:

  1. java.lang.IllegalThreadStateException (unchecked exception class): Thrown to indicate that a thread is not in an appropriate state for the requested operation.
  2. java.lang.ThreadDeath (unchecked exception class): It is a sub-class Error (in general programmer should not try to handle them). An instance of ThreadDeath is thrown in the victim thread when the stop method with zero arguments in class Thread is called. An application should catch instances of this class only if it must clean up after being terminated asynchronously. If ThreadDeath is caught by a method, it is important that it be rethrown so that the thread actually dies.
  3. java.lang.InterruptedException (checked exception class): Thrown when a thread is waiting, sleeping, or otherwise paused for a long time and another thread interrupts it using the interrupt method in class Thread.

Friday, 1 April 2011

J2ee: Introduction to JSP tags

The basic JSP component is the JSP tags. I (JBS) will provide you the general overview about the same. Here is a listing of the tags used in Java Server Pages:
  1. Declaration tag
  2. Expression tag
  3. Directive tag
  4. Scriptlet tag
  5. Action tag

Declaration tag:
Declaration tag is used to define functions, methods and variables that will be used in Java Server Pages.
Notation of the Declaration tag is given below:

"<%! ... %>"

General syntax of Declaration Tag:

<%!
// Variables or methods declaration
// This section will be launched at the traslated servlet class directly
Java statement 1;
Java statement 2;
...;
Java statement n;
%>

REMEMBER: Every Java statement will be terminated with (;)

For example:

<%!
private int n = 0 ;
public int meth( int sth)
{
//Java Statements ;
}
%>


Expression tag:
Expression tag is used to display output of any data on the generated page. The data placed in Expression tag prints on the output stream and automatically converts data into string. The Expression tag can contain any Java expression used for printing output equivalent to out.println().Thus, an expression tag contains a scripting language expression which is evaluated, automatically converts data to a String and the outputs are displayed.
Notation of Expression tag is given below:

<%= ... %>

General syntax of Expression Tag:

<%=
// This section will bw launched within the out.print() method, within _jspservice() method, within the translated servlet class
//Java Expression to be printed out
%>


For example:

<%=new java.util.Date() %>


Directive tag:
Directives are JSP elements that provide global information about an entire JSP page. An example would be a directive that indicated the language to be used in compiling a JSP page. The syntax of a directive is as follows:

<%@ directive {attribute="value"} %>

This states that, for this page directive, assign these values for these attributes. A directive can contain n number of optional attribute/value pairs. The following line of code would indicate that the JSP language to use would be Java:

<%@ page language="java" %>

There are three possible directives currently defined by the JSP specification: page, include, and taglib. Each one of these directives and their attributes, if applicable, are defined in the following sections.

  • The page Directive-
The page directive defines information that will be globally available for that JavaServer Page.

  • The include Directive-
The include directive is used to insert text and code at JSP translation time. The syntax of the include directive is as follows:

<%@ include file="relativeURLspec" %>

The file that the file attribute points to can reference a normal text HTML file or it can reference a JSP file, which will be evaluated at translation time.

  • The taglib Directive-
The most recent version of the JSP specification defines a mechanism for extending the current set of JSP tags. It does this by creating a custom set of tags called a tag library. That is what the taglib points to. The taglib directive declares that the page uses custom tags, uniquely names the tag library defining them, and associates a tag prefix that will distinguish usage of those tags. The syntax of the taglib directive is as follows:

<%@ taglib uri="tagLibraryURI" prefix="tagPrefix" %>


Scriptlet tag:
Scriptlets are what bring all the scripting elements together. They can contain any coding statements that are valid for the language referenced in the language directive. They are executed at request-time and they can make use of declarations, expressions, and JavaBeans. The syntax for a scriptlet is as follows:

<% scriptlet source %>

During the initial request the JSP scripting code is converted to servlet code and then compiled and loaded into resident memory. The actual source code, which is found between scriptlet tags <% ... %>, is placed into the newly created servlet's _jspService() method. See the following sample JSP source:

<% out.println("HELLO WORLD"); %>

It has a very simple scriptlet section that will print HELLO WORLD to the JspWriter implicit objectout.
You don't need to dig too deeply into the servlet code generated by the Web server, because it is generated for you. You just need to understand that it is being generated by the JSP engine and is the JSP equivalent to a servlet's service() method. It is also important to know that the JSP engine creates a servlet equivalent to the init() and destroy() methods.

Action tag:
Actions provide an abstraction that can be used to easily encapsulate common tasks. They typically create or act on objects, normally JavaBeans. The JSP technology provides some standard actions. These actions are defined in the following sections.

  • *jsp:useBean*
The *jsp:useBean* action associates an instance of a JavaBean defined with a given scope and ID, via a newly declared scripting variable of the same ID.

  • *jsp:setProperty*
The *jsp:setProperty* action sets the value of a bean's property.

  • *jsp:getProperty*
The *jsp:getProperty* action takes the value of the referenced bean instance's property, converts it to a java.lang.String, and places it into the implicit out object.

  • *jsp:include*
The *jsp:include* action provides a mechanism for including additional static and dynamic resources in the current JSP page. The syntax for this action is as follows:

*jsp:include page="urlSpec" flush="true" /*
and
*jsp:include page="urlSpec" flush="true"*
{ jsp:param ... /> }
*/jsp:include*

The first syntax example illustrates a request-time inclusion, whereas the second contains a list of param sub-elements that are used to argue the request for the purpose of inclusion.
N.B. Consider the stars as opening and closing angular brackets.