Wednesday, December 12, 2007

Work

There is no pleasure in having nothing to do; the fun is in having lots to do and not doing it.

courtesy : Anjali

War

War is young men dying and old men talking.

From the movie Troy

Tuesday, December 11, 2007

Happiness

Being happy doesn't mean everything is perfect. It means you have decided to look beyond the imperfections.

courtesy : Anjali

Monday, December 10, 2007

Java Interview FAQ

Below is a list of most frequently asked interview questions in Java. I am not furnishing any answers here because you can easily find them on google for one reason. And for many questions there is no single correct answer. So people are free to post their versions in the comments. Also, please do add to the list any other FAQ which I might have missed.
  1. Why is Java Platform independent? How does it acheive it?
  2. abstract class vs interface
  3. What is polymorphism?
  4. What is multiple inheritance? Does Java support it?
  5. overloading vs overriding
  6. String vs StringBuffer
  7. Why is String immutable? How do you make a class immutable?
  8. Hashtable vs HashMap
  9. What is multi-threading?
  10. How do you make a program multi-threaded?
  11. What is synchronized?
  12. What is final?
  13. final vs finally vs finalize
  14. How are Exceptions handled in Java?
  15. Checked Exception vs Unchecked/Runtime Exception
  16. What is serialization?
  17. What is singleton design pattern?
  18. What are inner classes?

Life

You need to keep running to stay where you are, because the world around you is running.

Thursday, December 6, 2007

Right vs Left

There is nothing Right in the Left brain while there is nothing Left in the Right brain.

courtesy : Priya

Deja Vu and Amnesia

Right now I am feeling Deja vu and Amnesia at the same time. I think I have forgot this before.

courtesy : baki

War

War does not determine who is right, just who is left.

courtesy : Priya

Wednesday, December 5, 2007

MySQL import data from flat file

Type the following SQL at the mysql prompt:

LOAD DATA LOCAL INFILE '/importfile.csv' INTO TABLE test_table FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (field1, filed2, field3);

This is taken from How do I import delimited data to MySQL where more details can be found.

Java Class Loader

In a J2SE 2 (that is, J2SE 1.2 or later) environment, class loaders are arranged in a parent-child tree. Normally, when a class loader is asked to load a particular class or resource, it delegates the request to a parent class loader first, and then looks in its own repositories only if the parent class loader(s) cannot find the requested class or resource.

A crisp article on Java Class Loading explains the concepts.

MySQL convert or cast int to string

Suppose you have a table with 2 columns one int and other varchar. Now if you want to update varchar fields in all the records with the int value, use this query :

update table_name set varchar_Field = CAST(int_Field AS CHAR);

If you want to some text in addition to the int field, then use :

update table_name set varchar_Field = CONCAT(CAST(int_Field AS CHAR), 'sampleText');

vi search and replace all

:%s /search_text/replace_text/g

If either of the search or replace texts has a forward-slash '/', use the backward-slash '\' to escape it.

Tuesday, November 13, 2007

Understanding Object wait()

The general rule of thumb to use the wait statement is as follows. This idiom addresses the issue of both missed notifications and early notifications.

synchronized(synclock) {
while (condition_does_not_hold) {
syncLock.wait();
}
// Perform action appropriate to condition
}
// Perform action that needs to be done outside the synchronized block

When wait is called on an Object's instance ...
The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

Tuesday, November 6, 2007

Double-Checked Locking

Here is a very good article on Double-Checked Locking

I liked the 4th method a lot - On Demand Lazy Initialization. Using simple concepts and achieving solution to complex problem.

"Static classes are not initialized until needed and the initialization is guaranteed to be thread-safe."

Monday, November 5, 2007

Telugu font rendering in Ubuntu Feisty Fawn

Copy and Paste these commands and restart machine or XSession(Ctrl+Alt+Backspace)
  • sudo apt-get install ttf-telugu-fonts ttf-indic-fonts language-pack-te
  • wget http://abhiomkar.googlepages.com/lohit_te.ttf
  • sudo cp lohit_te.ttf /usr/share/fonts/truetype/ttf-telugu-fonts/
  • sudo fc-cache
This information is taken from Abhinay's Blog

Friday, October 19, 2007

Install of MySQL/PHPMyAdmin aka LAMP (Linux Apache MySQL PHP)

  • sudo apt-get install mysql-server
  • sudo apt-get install apache2
  • sudo apt-get install php5
  • sudo apt-get install php5-mysql
  • sudo apt-get install phpmyadmin

More information is available at the this link

Here is the link giving step by step instructions for getting mysql/apache/php and phpmyadmin working. Tells you how to set up mysql user too.

Wednesday, October 17, 2007

How to run pre-Vista programs in Compatibility Mode

The Windows Fanatics weblog details how to use Vista's Compatibility Mode to run apps that aren't quite Vista ready. Here's how:

1. Right click the executable and click the Properties option.
2. Select the Compatibility tab.
3. Select the Run This Program in Compatibility Mode option.
4. From the drop-down list, choose the operating system you ran before upgrading to Vista.
5. If necessary, select the option to run the program as an administration.
6. Click OK.

This post is contributed by baki. He can reached at bhanukiran.j@gmail.com

Debug Remote Java application

The java process should start with the following arguments :
-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n

In addition to that the code should be compiled(using javac) with debug option -g

Task Manager/Process List in Kubuntu

ps gives a list of processes. Alternately the short-cut Ctrl+Esc can be used to get a graphical list of processes running

apt-get behind fire-wall or proxy

A link on apt-get behind proxy

Google Talk in Kubuntu

A good article on Google Talk in Kubuntu

Python MySQL library support

Try the following at the python prompt.

>>> import _mysql
If the error is something like this :
Traceback (most recent call last):
    File "", line 1, in
        ImportError: No module named _mysql

Then try apt-get install python-mysqldb

Single/Double click in KDE/Kubuntu

System Settings->Keyboard and Mouse->Mouse->General->Icons

A much more informative entry can be found at Disable Single-Click Opening of Files in KDE

KDE/Kubuntu Hide/Restore Menu Bar

Menu Bar in KDE/Kubuntu Konquerer can be hidden by Settings->Hide Menu Bar. But there is no way to restore it without the keyboard shortcut for hide/restore Ctrl+M

Wednesday, September 26, 2007

Amarok MP3 support in Kubuntu

For Kubuntu 6.10 (Edgy Eft)

• Open Amarok and play an MP3 file. Amarok will ask if you would like to add MP3 support.
• Open Synaptic Package Manager and install the libxine-extracodecs package.

For Kubuntu 7.04 (Feisty Fawn)

• Open Synaptic Package Manager, search and install the package libxine1-ffmpeg.

For more information goto How to Repair MP3 Support in Kubuntu

Kubuntu Linux FTP

sudo apt-get install vsftpd

vi /etc/vsftp.conf

set local_enable=YES

For more information visit Ubuntu Linux vsftpd ftp service / server install, configuration howto

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.

Tuesday, July 31, 2007

Theory and Practice

A good quote

In theory, there is no difference between theory and practice. But, in practice, there is. -- Jan L. A. van de Snepscheut/Yogi Berra

Java Thread Synchronization - Must know facts

Below is a link to a good article on Thread synchronization

Thread Synchronization

Friday, July 27, 2007

My First Post

This is my first post in a blog. This will mark my entry into this latest world of blogging. Though I am late, its always better late than never.

I will start off with a nice quote which I came across recently.

Time is a great teacher, but unfortunately it kills all its pupils. -- Louis Hector Berlioz

So true.... isn't it ??