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.

Thursday, 31 March 2011

J2ee: About JavaBean

Let me (JBS) provide you a simplest look at what a bean is. A JavaBean is a 100% Java component that works on any Java Virtual Machine.
The minimum requirements that make a component a JavaBean are as follows:
  1. It must support the JDK 1.1 and later Serialization model.
  2. It must use get/set accessors to expose its properties.
There is nothing magical about creating a JavaBean. You just create a Java class that implements the java.io.Serializable interface and uses public get/set methods to expose its properties.
The following listing provide you a simple JavaBean:

import java.io.Serializable;
public class SimpleJavaBean implements java.io.Serializable
{
private String simpleProperty = new String("");
public SimpleJavaBean() { }
public String getSimpleProperty()
{
return simpleProperty;
}
public void setSimpleProperty(String value)
{
simpleProperty = value;
}
}

This class is now a JavaBean. It satisfies the minimum requirements. You can now load the SimpleJavaBean into any JavaBeans–aware program that uses introspection and change its properties. Its state can then be saved and reloaded anytime, because of its support for serialization.
Let's take a look at an example that illustrates how to serialize our new bean. The second example on the next listing creates an instance of our SimpleJavaBean, sets the simpleProperty to "simple property value", serializes the bean to a file, reads the bean back in, and finally displays proof that its state was maintained.

import java.io.*;
public class SimpleJavaBeanTester
{
public SimpleJavaBeanTester() { }
public void storeBean(SimpleJavaBean value)
{
try
{
// Create the ObjectOutputStream passing it the
// FileOutputStream object that points to our
// persistent storage.
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("file.dat"));
// Write the SimpleJavaBean to the ObjectOutputStream
os.writeObject(value);
os.flush();
os.close();
}
catch (IOException ioe)
{
System.err.println(ioe.getMessage());
}
}
public SimpleJavaBean getBean()
{
SimpleJavaBean value = null;
try
{
// Create the ObjectInputStream passing it the FileInputStream object that points to our persistent storage.
ObjectInputStream is = new ObjectInputStream(new FileInputStream("file.dat"));
// Read the stored object and downcast it back to a SimpleJavaBean
value = (SimpleJavaBean)is.readObject();
is.close();
}
catch (IOException ioe)
{
System.err.println(ioe.getMessage());
}
catch (ClassNotFoundException cnfe)
{
System.err.println(cnfe.getMessage());
}
return value;
}
public void testBean()
{
// Create the Bean
SimpleJavaBean simpleBean = new SimpleJavaBean();
// Use accessor to set property
simpleBean.setSimpleProperty("simple property value");
// Serialize the Bean to a Persistent Store
storeBean(simpleBean);
// Get the Bean from the Persistent Store
SimpleJavaBean newBean = getBean();
System.out.println("The newBean's simpleProperty == " +newBean.getSimpleProperty());
}
public static void main(String[] args)
{
SimpleJavaBeanTester simpleJavaBeanTester = new SimpleJavaBeanTester();
simpleJavaBeanTester.testBean();
try
{
System.out.println("Press enter to continue...");
System.in.read();
}
catch (IOException ioe)
{
System.err.println(ioe.getMessage());
}
}
}

J2ee: The Life Cycle of a Servlet

The life cycle of a Java servlet is a very simple object-oriented design. A servlet is constructed and initialized. It then services zero or more requests until the service that it extends shuts down. At this point the servlet is destroyed and garbage collected. This design explains why servlets are such a good replacement for CGI. The servlet is loaded only once and it stays resident in memory while servicing requests.
The interface that declares this framework is the javax.servlet.Servlet interface. The Servlet interface defines the life cycle methods. These methods are init(), service(), and destroy(). But before the init() call, a without argument constructor is invoked.

init()
The init() method is where the servlet's life begins. It is called by the server immediately after the servlet is instantiated. It is called only once. In the init() method, the servlet creates and initializes any resources, including data members, that it will be using while handling requests. The init() method's signature is defined as follows:

  • public void init(ServletConfig config) throws ServletException;
The init() method takes a ServletConfig object as a parameter. You should save this object so that it can be referenced later. The most common way of doing this is to have the init() method call super.init(), passing it the ServletConfig object.
The init() method can throw a ServletException. If, for some reason, the servlet cannot initialize the resources necessary to handle requests, the init() method will throw a ServletException.

service()
The service() method handles all requests sent by a client. It cannot start servicing requests until the init() method has been executed. You will not usually implement this method directly, unless you extend the GenericServlet abstract class.
The most common implementation of the service() method is in the HttpServlet class. The HttpServlet class implements the Servlet interface by extending GenericServlet. Its service() method supports standard HTTP/1.1 requests by determining the request type and calling the appropriate method. The signature of the service() method is as follows:

  • public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException;
The service() method implements a request and response paradigm. The ServletRequest object contains information about the service request, encapsulating information provided by the client. The ServletResponse object contains the information returned to the client.

destroy()
This method signifies the end of a servlet's life. When a service is being shut down, it calls the servlet's destroy() method. This is where any resources that were created in the init() method will be cleaned up. If you have an open database connection, you should close it here. This is also a good place to save any persistent information that will be used the next time the servlet is loaded. The signature of the destroy() is as follows:

  • public void destroy();

Wednesday, 30 March 2011

DBMS: DK/NF (Domain/Key Normal Form)

Unlike previously defined normal forms, DK/NF is not defined in terms of traditional dependencies (functional, multivalued, or join). It was introduced by Ron Fagin in his paper "A Normal Form for Relational Databases that Is Based on Domains and Keys," ACM TODS 6, No. 3 (September 1981). Instead, it is defined in terms of the more primitive concepts of domain and key, along with the general concept of a “constraint.”
A domain constraint specifies the permissible values for a given attribute, while a key constraint specifies the attributes that uniquely identify a row in a given table. That is, A domain constraint--better called an attribute constraint--is simply a constraint to the effect a given attribute A of R takes its values from some given domain D. A key constraint is simply a constraint to the effect that a given set A, B, ..., C of R constitutes a key for R. To be specific, enforcing domain constraints just means checking that attribute values are always values from the applicable domain (i.e., values of the right type); enforcing key constraints just means checking that key values are unique.
By definition it is a normal form used in database normalization which requires that the database contains no constraints other than domain constraints and key constraints. That is, a relation schema is in DK/NF if every constraint can be inferred by simply knowing the set of attribute names and their underlying domains, along with the set of keys.
However, successfully building a domain/key normal form database remains a difficult task, even for experienced database programmers. Thus, while the domain/key normal form eliminates the problems found in most databases, it tends to be the most costly normal form to achieve. However, failing to achieve the domain/key normal form may carry long-term, hidden costs due to anomalies which appear in databases adhering only to lower normal forms over time. After transforming a database into DK/NF there would be no insertion or deletion anomalies.
The trouble is, lots of relvars aren't in DK/NF in the first place. For example, suppose there's a constraint on R to the effect that R must contain at least ten tuples. Then that constraint is certainly not a consequence of the domain and key constraints that apply to R, and so R isn't in DK/NF. The sad fact is, not all relvars can be reduced to DK/NF; nor do we know the answer to the question "Exactly when can a relvar be so reduced?".
Now, it's true that Fagin proves in his paper that if relvar R is in DK/NF, then R is automatically in 5NF (and hence 4NF, BCNF, etc.) as well. However, it's wrong to think of DK/NF as another step in the progression from 1NF to 2NF to ... to 5NF, because 5NF is always achievable, but DK/NF is not.
It's also wrong to say that there are "no normal forms higher than DK/NF." In CODD's recent work -- documented in the book TEMPORAL DATA AND THE RELATIONAL MODEL, he has come up with a new sixth normal form, 6NF. 6NF is higher than 5NF (all 6NF relvars are in 5NF, but the converse isn't true); moreover, 6NF is always achievable, but it isn't implied by DK/NF. In other words, there are relvars in DK/NF that aren't in 6NF.
Sometimes it is asked: "If a [relvar] has an atomic primary key and is in 3NF, is it automatically in DK/NF?" No. If the EMP relvar just shown is subject to the constraint that there must be at least ten employees, then EMP is in 3NF (and in fact 5NF) but not DK/NF.

For further study: