Wednesday, August 29, 2007

Wednesday, August 22, 2007

How to print Hello World ! without using main in Java?

This is probably a very old question, but as the blog title goes, I just discovered it today.


//Example.java

public class Example
{
static {
System.out.println( "Hello World" );
System.exit(0);
}
}

javac Example.java
java Example

The code is stunningly simple. But there are some good concepts involved in it.
1. Always static blocks are executed first.
On typing java Example, JVM first loads that class, which starts with initializing static variables followed by static blocks and then static methods.
2. JVM searches for public static void main(String[] abc) while executing a class.
If JVM does not find it, it throws a java.lang.NoSuchMethodError. But here in the above example, even before letting the JVM do that, System.exit(0) is called.

Solution might look easy after seeing it. But its always the case, isnt it ???

Tuesday, August 14, 2007

How to modify Oracle LOBS/BLOBS/CLOBS

To modify a LOB,
SELECT id, blob FROM test FOR UPDATE

Note that you must use "FOR UPDATE" in the select statement or you will receive "ORA-22920: row containing the LOB value is not locked" when writing to the LOB.

The above lines are taken from the below link :
How to use Oracle LOBS/BLOBS/CLOBS

Tuesday, August 7, 2007

Java Runtime.exec() - a few exceptions :)

Java's Runtime.exec() wont work always as expected. Here is a link which describes those situations and give a solution to workaround them.
When Runtime.exec() won't work

Cloning Java objects using serialization

An excellent article on Cloning, Versioning, Serialization etc.
Cloning Java objects using serialization

Java Serialization

Below is the link to an exhaustive article with respect to Java Serialization basics.
Discover the secrets of the Java Serialization API

The Singleton pattern

The Singleton pattern is an object-oriented design pattern used to ensure that a class has only one instance and provide a global point of access to that instance. The Singleton pattern can be implemented by doing the following:
  • Implementing a static method that returns an instance of the class
  • Making the constructor private so a class instance can be created only through the static method
  • Using a static variable to store the class instance

Static Objects - Garbage Collection

When I said 'Static Objects' I meant an Object whose reference is held by a static variable.

In Java, usually a class member (variable or method) is accessed in conjunction with an object of its class. In the case of static variables and methods, it is possible to use a class member without creating an instance of its class. A class with static members is known as a static class. In such cases, before a class instance is created, an object of its class will also be created by the JVM. The class object is allocated to the heap itself. The primordial class loader will load the class object. In the case of static classes, all the static members will also be instantiated along with the class object. Once the variable is initialized with data (typically an object), the variable remains in memory as long as the class that defines it stays in memory. If the primordial class loader loads class instances, they will stay in memory for the duration of the program and are not eligible for garbage collection. So static classes and associated static variables will never be garbage collected. Thus, using too many static variables leads to memory leaks.

Recommendation
Usage of static classes should be minimized as they stay in memory for the lifetime of the application.

Daemon Thread

A daemon thread is a thread that has no other role other than to serve other threads. When only daemon threads remain, the program exits. When a new thread object is created, the new thread has priority equal to the creating thread, and is a daemon thread if and only if the creating thread is a daemon.

Java finalize()

For any given object, finalize() will be called only once by the garbage collector.
Calling finalize() can actually result in saving an object from deletion.

Any exception thrown by finalize() during garbage collection halts the finalization but is otherwise ignored
finalize() is never run more than once on any object

In the finalize() method you could write code that passes a reference to the object in question back to another object, effectively uneligiblizing the object for garbage collection. If at some point later on this same object becomes eligible for garbage collection again, the garbage collector can still process this object and delete it. The garbage collector, however,will remember that, for this object, finalize() already ran, and it will not run finalize() again.

One reasonable, though rare, application for a finalizer is to free memory allocated by native methods. If an object invokes a native method that allocates memory (perhaps a C function that calls malloc()), that object's finalizer could invoke a native method that frees that memory (calls free()). In this situation, you would be using the finalizer to free up memory allocated on behalf of an object -- memory that will not be automatically reclaimed by the garbage collector.

Another, more common, use of finalizers is to provide a fallback mechanism for releasing non-memory finite resources such as file handles or sockets. As mentioned previously, you shouldn't rely on finalizers for releasing finite non-memory resources. Instead, you should provide a method that will release the resource. But you may also wish to include a finalizer that checks to make sure the resource has already been released, and if it hasn't, that goes ahead and releases it. Such a finalizer guards against (and hopefully will not encourage) sloppy use of your class. If a client programmer forgets to invoke the method you provided to release the resource, the finalizer will release the resource if the object is ever garbage collected.

If you feel you simply must bring an object back to life, consider cloning a new copy of the object instead of resurrecting the same old object. The reasoning behind this piece of advice is that garbage collectors in the JVM invoke the finalize() method of an object only once. If that object is resurrected and becomes available for garbage collection a second time, the object's finalize() method will not be invoked again.

Invoking superclass finalizers is good practice in any finalizer, even in cases where no superclass exists other than Object. The JVM does not automatically invoke superclass finalizers, so you must do so explicitly.


The most important point to take away from this article is that if a Java object needs to take some action at the end of its life, no automatic way exists in Java that will guarantee that action is taken in a timely manner. You can't rely on finalizers to take the action, at least not in a timely way. You will need to provide a method that performs the action and encourage client programmers to invoke the method when the object is no longer needed.


This article contained several guidelines that pertain to finalizers:
Don't design your Java programs such that correctness depends on "timely" finalization

Don't assume that a finalizer will be run by any particular thread

Don't assume that finalizers will be run in any particular order

Avoid designs that require finalizers to resurrect objects; if you must use resurrection, prefer cloning over straight resurrection

Remember that exceptions thrown by finalizers are ignored

If your program includes objects with finalizers that absolutely must be run before the program exits, invoke runFinalizersOnExit(true) in class Runtime or System

Unless you are writing the finalizer for class Object, always invoke super.finalize() at the end of your finalizers

More information can be obtained from the following link :
finalize()

Java equals() and hashcode

The hashCode() method exists purely for efficiency. The Java platform architects anticipated the importance of hash-based collection classes -- such as Hashtable, HashMap, and HashSet -- in typical Java applications, and comparing against many objects with equals() can be computationally expensive. Having every Java object support hashCode() allows for efficient storage and retrieval using hash-based collections.


Room for improvement?

Building hashing into the root object class of the Java class library was a very sensible design compromise -- it makes using hash-based containers so much easier and more efficient. However, several criticisms have been made of the approach to and implementation of hashing and equality in the Java class library. The hash-based containers in java.util are very convenient and easy to use, but may not be suitable for applications that require very high performance. While most of these will never be changed, it is worthwhile to keep in mind when you're designing applications that rely heavily on the efficiency of hash-based containers. These criticisms include:
Too small a hash range. Using int, instead of long, for the return type of hashCode() increases the possibility of hash collisions.

Bad distribution of hash values. The hash values for short strings and small integers are themselves small integers, and are close to the hash values of other "nearby" objects. A more well-behaved hash function would distribute the hash values more evenly across the hash range.

No defined hashing operations. While some classes, such as String and List, define a hash algorithm to be used in combining the hash values of its constituent elements into a single hash value, the language specification does not define any approved means of combining the hash values of multiple objects into a new hash value. The trick used by List, String, or the example class A discussed earlier in Writing your own equals() and hashCode() methods are simple, but far from mathematically ideal. Nor does the class library offer convenience implementations of any hashing algorithm that would simplify the creation of more sophisticated hashCode() implementations.

Difficulty writing equals() when extending an instantiable class that already overrides equals(). The "obvious" ways to define equals() when extending an instantiable class that already overrides equals() all fail to meet the symmetry or transitivity requirements of the equals() method. This means that you must understand the structure and implementation details of classes you are extending when overriding equals(), and may even need to expose private fields in the base class as protected to do so, which violates principles of good object-oriented design.