Saturday, November 8, 2008

Simply Singleton

We all know how objects are instantiated right? Maybe not everyone? Let's go through a quick refresher.

Objects are instantiated by using the new keyword. The new keyword allows you to create a new instance of an object, and to specify parameters to the class's constructor. You can specify no parameters, in which case the blank constructor (also known as the default constructor) is invoked. Constructors can have access modifiers, like public and private, which allow you to control which classes have access to a constructor. So to prevent direct instantiation, we create a private default constructor, so that other classes can't create a new instance.

We'll start with the class definition, for a SingletonObject class. Next, we provide a default constructor that is marked as private. No actual code needs to be written, but you're free to add some initialization code if you'd like.

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}
}

So far so good. But unless we add some further code, there'll be absolutely no way to use the class. We want to prevent direct instantiation, but we still need to allow a way to get a reference to an instance of the singleton object.

Getting an instance of the singleton

We need to provide an accessor method, that returns an instance of the SingletonObject class but doesn't allow more than one copy to be accessed. We can manually instantiate an object, but we need to keep a reference to the singleton so that subsequent calls to the accessor method can return the singleton (rather than creating a new one). To do this, provide a public static method called getSingletonObject(), and store a copy of the singleton in a private member variable.

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}

public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}

private static SingletonObject ref;
}

So far, so good. When first called, the getSingletonObject() method creates a singleton instance, assigns it to a member variable, and returns the singleton. Subsequent calls will return the same singleton, and all is well with the world. You could extend the functionality of the singleton object by adding new methods, to perform the types of tasks your singleton needs. So the singleton is done, right? Well almost.....

Preventing thread problems with your singleton

We need to make sure that threads calling the getSingletonObject() method don't cause problems, so it's advisable to mark the method as synchronized. This prevents two threads from calling the getSingletonObject() method at the same time. If one thread entered the method just after the other, you could end up calling the SingletonObject constructor twice and returning different values. To change the method, just add the synchronized keyword as follows to the method declaration :-

public static synchronized
SingletonObject getSingletonObject()

Are we finished yet?

There, finished. A singleton object that guarantees one instance of the class, and never more than one. Right? Well.... not quite. Where there's a will, there's a way - it is still possible to evade all our defensive programming and create more than one instance of the singleton class defined above. Here's where most articles on singletons fall down, because they forget about cloning. Examine the following code snippet, which clones a singleton object.

public class Clone
{
public static void main(String args[])
throws Exception
{
// Get a singleton
SingletonObject obj =
SingletonObject.getSingletonObject();

// Buahahaha. Let's clone the object
SingletonObject clone =
(SingletonObject) obj.clone();

}
}

Okay, we're cheating a little here. There isn't a clone() method defined in SingletonObject, but there is in the java.lang.Objectclass which it is inherited from. By default, the clone() method is marked as protected, but if your SingletonObject extends another class that does support cloning, it is possible to violate the design principles of the singleton. So, to be absolutely positively 100% certain that a singleton really is a singleton, we must add a clone() method of our own, and throw a CloneNotSupportedException if anyone dares try!

Here's the final source code for a SingletonObject, which you can use as a template for your own singletons.

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}

public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}

public Object clone()
throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
// that'll teach 'em
}


private static SingletonObject ref;
}


Preventing direct instantiation

//sample code
package com.test.corejava;

/**
*
* @author seetharam
*/
public class TestSingleton {

private static TestSingleton instance;

// Private constructor suppresses generation of a (public) default constructor

private TestSingleton() {

// logic code is not req'd
}



public static TestSingleton getInstance() {

//acquiring the lock to the class's obj
synchronized (TestSingleton.class) {

if (instance == null) {

instance = new TestSingleton();
}
}

return instance;

}

public Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
// that'll teach 'em
}
}


Summary

A singleton is an class that can be instantiated once, and only once. This is a fairly unique property, but useful in a wide range of object designs. Creating an implementation of the singleton pattern is fairly straightforward - simple block off access to all constructors, provide a static method for getting an instance of the singleton, and prevent cloning.

struts-hibernate-integration-tutorial

this is the page where we can get the info like to struts-hibernate Integration in a step by step basis.click here,

JSP Compiler

-we can compile a JSP manually.
here,
The JSP compiler(JSPC) depends on the Web Container.
we take, BEA WebLogic Application Server.

1.goto DOS Shell and run "setEnv.cmd"
2.using cd command move to the JSP file directory.
3.run " java weblogic.jspc -keepgenerated JspOne.jsp "

note : if " -keepgenerated " is not used on above command,
the JSPCompiler removes the .java file which is generated by JSPC.

Friday, November 7, 2008

Serializing and Deserializing Objects

The serialization mechanism in Java provides the means for persisting objects beyond a single run of a Java program. To serialize an object, make sure that the declaring class implements the java.io.Serializable interface. Then obtain an ObjectOutputStream to write the object to and call the writeObject() method on the ObjectOutputStream. To deserialize an object, obtain an ObjectInputStream to read the object from and call the readObject() method on the ObjectInputStream. The following code excerpts illustrate how an object of type MyClass is serialized and deserialized.


1. // Serialize an object of type MyClass
2. MyClass myObject = new MyClass();
3. FileOutputStream fos = new FileOutputStream("myObject.ser");
4. ObjectOutputStream oos = new ObjectOutputStream(fos);
5. oos.writeObject(myObject);
6. oos.flush();
7. oos.close();
8.
9. // Deserialize the object persisted in "myObject.ser"
10. FileInputStream fis = new FileInputStream("myObject.ser");
11. ObjectInputStream ois = new ObjectInputStream(fis);
12. MyClass myDeserializedObject = (MyClass)ois.readObject();
13. ois.close();

Lines 1-5 serialize the object myObject of type MyClass. On Line 3, the file output stream fos is created for the file named myObject.ser. The object is actually persisted in this file on Lines 5-7. Lines 9-13 read the object back from the file myObject.ser. If you list the files in the directory where this code's .class file is stored, you will see a new file called myObject.ser added to the listing. The Lines 1-7 and 9-13 can be in two completely different processes run at different times.

Thursday, November 6, 2008

What is the purpose of finalization ?

protected void finalize() throws Throwable

* Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.
The general contract of finalize is that it is invoked if and when the JavaTM virtual machine has determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, except as a result of an action taken by the finalization of some other object or class which is ready to be finalized. The finalize method may take any action, including making this object available again to other threads; the usual purpose of finalize, however, is to perform cleanup actions before the object is irrevocably discarded. For example, the finalize method for an object that represents an input/output connection might perform explicit I/O transactions to break the connection before the object is permanently discarded.

* The finalize method of class Object performs no special action; it simply returns normally. Subclasses of Object may override this definition.
The Java programming language does not guarantee which thread will invoke the finalize method for any given object. It is guaranteed, however, that the thread that invokes finalize will not be holding any user-visible synchronization locks when finalize is invoked. If an uncaught exception is thrown by the finalize method, the exception is ignored and finalization of that object terminates.
After the finalize method has been invoked for an object, no further action is taken until the Java virtual machine has again determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, including possible actions by other objects or classes which are ready to be finalized, at which point the object may be discarded.
The finalize method is never invoked more than once by a Java virtual machine for any given object.

* Any exception thrown by the finalize method causes the finalization of this object to be halted, but is otherwise ignored.

* While exception handling if exception is thrown programme will abort abnormally but it can leads to some problamatic situation..hence we have to ensure some code will always run whtever happen..finalization does so. Some useful tasks that we have to do ( cleaning up some resources or closing some connection or socket etc) we can gurantee it will be done by simply putting it in finally block.

* It will run always (Unless System.exit() is not called) and
hence future problem can be handled.

* finally block, finalize() - performed by the JVM,before calling GC

Wednesday, November 5, 2008

A sample code of "Thread implements Runnable"

package com.test;

/**
*
* @author seetharam
*/

public class TestThread implements Runnable{

Thread myThread;

public TestThread()
{
System.out.println("in init() -- starting thread.");
myThread= new Thread(this);
myThread.start();
}


public void run()
{
int i=0;
for(;;)
{

System.out.println("At " + i + " and counting!");
try {myThread.sleep(1000);
i++;
}
catch (InterruptedException e ) {}

}
}
public static void main(String a[]){
TestThread obj=new TestThread();

}
}

Sunday, November 2, 2008

can a lock be acquired on a class ? reply : Yes, we can.

By using synchronize block on obj.here, a ClassName.class can return an object


package com.test;

/**
*
* @author thanooj
*/

public class Emp {

private int eno;
private String ename;
private double sal;
public Emp(int eno,String ename,double sal){
this.eno=eno;
this.ename=ename;
this.sal=sal;
}
public int getEno(){
return eno;
}
public String getEname(){
return ename;
}
public double getSal(){
return sal;
}
}
``````````````````````````````````````````````````
package com.test;

/**
*
* @author thanooj
*/

public class Dept {
private int dno;
private String dname;
private Emp emp;
public Dept(int dno,String dname){
this.dno=dno;
this.dname=dname;
}
public int getDno(){
return dno;
}
public String getDname(){
return dname;
}
public Emp getEmp(){
return emp;
}

public void addEmp(Emp emp){
synchronized(Emp.class){
this.emp=emp;

// our Complex Operations

}


}
}
```````````````````````````````````````````````````

package com.test;

/**
*
* @author thanooj
*/

public class TestLockAClass {
public static void main(String a[]){

Emp emp=new Emp(1,"rama",50000.01);
System.out.print(emp.getEno()+" "+emp.getEname()+" "+emp.getSal());
Dept dept =new Dept(10,"developer");
dept.addEmp(emp);
System.out.println();
System.out.print(dept.getDno()+" "+dept.getDname());
System.out.println();
System.out.println(dept.getEmp().getEno()+" "+dept.getEmp().getEname()+" "+dept.getEmp().getSal());
}
}

output
--------
1 rama 50000.01
10 developer
1 rama 50000.01