Monday, November 25, 2013

Marker Interfaces Vs Marker Annotations as Type definers

When it comes to defining types, there's always some debate between using Marker Interfaces vs Marker Annotations. To appreciate the discussion its important to understand what are marker interfaces. Well, a marker interface is merely an interface that contains "no" method declaration and it just designates the implementing class as having some unique characteristic, e.g. the Serializable interface. On the other hand, Marker annotations are just annotations whose sole purpose is also to designate a class/method/variable to have a certain characteristic. So when do you use marker interface and when would you use an annotation to define a type in java?

The key here is to understand the intent of the usage. Let me elaborate on this. We know that only classes and interfaces that implement/extend other interfaces. Clearly you must use an annotation if the marker applies to any
program element other than a class or interface, as only classes and interfaces can
be made to implement or extend an interface. But if we believe that our end requirement of type definition could be such wherein I have to supply an class of a specific type as an argument to method, one should use a Marker interface for defining this type as it would also help in comple-time checking of the client code (remember this could be achieved even with Marker Annotation but since annotation processing does not happen till run-time there is no way to know at compile time of the contract was honoured by the client class). As an extension of this point if we believe that we want to limit the use of this marker interface to elements of a particular interface the it makes sense to define the marker as a subinterface of that interface. Therefore, marker interfaces are targeted more precisely.

But its unfair to assume that Marker annotations do not have their use. Their main advantage is that Annotations are evolutionary and this is precisely a major problem with interfaces. Interfaces cannot evolve over time. Once the contract is published especially the public interfaces, its nearly impossible to change it. On the other hand annotations can evolve into a richer annotation type over time. Annotations should be used as meta-definitions and this usage also helps to create much better code processing tools.

Friday, July 19, 2013

Taking Backup of MySQL Database with stored procedures and functions.

mysqldump is a utility to take a backup of MySQL database. With MySQL 5 new features like stored procedures and triggers were introduced. mysqldump by default backups only the triggers and not the stored procedures or functions. This behaviour can however be controlled by the following two parameters:

1. routines (--routines)
2. triggers (--triggers)

routines option is by default false while triggers option is by default true.

An example to take a backup of your database along with stored procedures, functions and triggers:
    # mysqldump --routines -u 'username' -p'password' > mysqldummpfile.sql

Let’s assume we want to backup only the stored procedures,functions and triggers and not the mysql tables and data , then we should run something like this:

   # mysqldump --routines --no-create-info --no-data --no-create-db --skip-opt -u 'username' -p'password' > mysqldumpwithoutanytablesanddata.sql

This will backup only the procedures triggers and functions of the Database.

For importing this backup procedure remains the same (irrespective of whether the backup was taken with or without routines):

   mysql -u 'username' -p'password' < mysqldumpwithoutanytablesanddata.sql


Wednesday, November 21, 2012

Debugging Shell Scripts in Unix

Debugging is an important part of your overall development process. Unfortunately not many developers know that even shell scripts can be debugged. The good thing is debugging shell scripts is just about knowing a few options of the 'sh' command. Lets see how we can debug the shell scripts.

To see exactly where the script produces an error use the 'sh' command with a 'x' option:

sh -x myscript.sh your-arguments-if-you-hahve

When you run the above command you can see each statement with their output printed in the next line.

For example if i have a script which does addition of two numbers given by the user like:

#!/bin/sh
echo $1
echo $2
echo $(($1 + $2))

The output of 'sh -x myscript.sh 3 4' would be

+ echo 3
3
+ echo 4
4
+ echo 7
7

So, we see the statement and its output in the next line.

Other options are:

-e in non-interactive mode, exit immediately if a command fails.

-v print shell input lines as they are read.

-n read commands but do not execute them.

In the other options 'v' is probably a really good option to explore. If i run my above script with '-v' option then the following output would be seen:

sh -v myscript.sh 3 4

#!/bin/sh
echo $1
3
echo $2
4
echo $(($1 + $2))
7

This is again a good option to explore.


Thursday, September 13, 2012

Recursive Automatic download of FTP files in Unix

With unix there comes numerous built in beautiful utilities. If one understands these utilities fully, he/she can accomplish seemingly difficult tasks in a jiffy.

One such thing that we always try to do it downloading a bunch of files from a FTP site. This becomes even tricky if there are many sub folders.

One such utility is wget.

A command line to recursively download all the files from an FTP location:

wget -r ftp://user:password@myremotehost -o /tmp/log &

'&' will make the process background, and output in /tmp/log file.

Easy money.


Sunday, August 5, 2012

Though personally I am not too much in favor of singletons but its a good brain exercise to see different ways in which it could be implemented.

The standard way as we all know is you have a final class (ideally purely for performance optimizations) with a private constructor and a public static getter method. I personally like to create the singleton object eagerly. It saves all the hassles to keep the getter method synchronized and therefore, make it a lot more scalar.

With the advent of generics, their application with different data structures and design patterns evolved and so did a couple of variants of Singleton.

class GenericSingleton {

private static final GenericSingleton instance = new GenericSingleton();
private GenericSingleton(){ }
public static GenericSingleton getInstance()
{
return (instance);
}
}

There is one more way to implement this and that being creating a map of identifiers and their classes but personally i prefer the above way as i prefer casting being kept out of the singleton itself.

Wednesday, June 27, 2012

One obviously knows a lot of different methods to implement singleton in java. Singleton by definition means one object per classloader. Starting Java 5 we now have enums which are first class singleton objects. The best method in java for implementing singletons is via enum(s).

Lets take a look with an example of a DB connection pool manager. We're using Data source to get connections:

public enum DBConnectionManager {
INSTANCE;

private DataSource ds = null;
private Lock connectionLock = new ReentrantLock();

DBConnectionManager() {
try {
final Context initCtx = new InitialContext();
final Context envCtx = (Context) initCtx.lookup("java:comp/env");
ds = (DataSource) envCtx.lookup("jdbc/DBConnectionManager");
} catch (NamingException e) {
e.printStackTrace();
}
}

public Connection getConnection() throws SQLException {
if(ds == null) return null;

Connection conn = null;
connectionLock.lock();
try {
conn = ds.getConnection();
} finally {
connectionLock.unlock();
}

return conn;
}
}


Since we are using connection pooling, we do not really need to close the connection and it's the responsibility of the calling code to close the connection (which actually does nothing but returns the connection back to the pool).

Wednesday, June 6, 2012



Get a list of all the running Threads in the current JVM and its origination


Sometimes, it makes sense to know the list of all running threads in the JVM. Either when you are creating your own profiling tool, or, when you need to monitor the health of your system and need meta-information of your platform. You may also need the information of all running threads when you would like to selectively, say 'stop' the threads (a technique i would showcase in my subsequent posts).


There are two ways to get it:

1. The long way:


Get the root thread group. and then call the enumerate() function on the root group repeatedly.


ThreadGroup rootGroup = Thread.currentThread( ).getThreadGroup( );
ThreadGroup parentGroup;
while ( ( parentGroup = rootGroup.getParent() ) != null ) {
rootGroup = parentGroup;
}



Thread[] threads = new Thread[ rootGroup.activeCount() ];
while ( rootGroup.enumerate( threads, true ) == threads.length ) {
threads = new Thread[ threads.length * 2 ];
}

for(Thread t : threads)
{
System.out.println("Thread name:"+t.getName());
StackTraceElement[] stackTraceElements = t.getStackTrace();
for(StackTraceElement s: stackTraceElements)
{
System.out.println("class name="+s.getClassName()+" and method name="+s.getMethodName()+" at line no.="+s.getLineNumber() );
}
}


2. The short way:


Set threadSet = Thread.getAllStackTraces().keySet();
//now just for displaying get the threads
threads = threadSet.toArray(new Thread[threadSet.size()]);
for(Thread t : threads)
{
System.out.println("Thread name:"+t.getName());
StackTraceElement[] stackTraceElements = t.getStackTrace();
for(StackTraceElement s: stackTraceElements)
{
System.out.println("class name="+s.getClassName()+" and method name="+s.getMethodName()+" at line no.="+s.getLineNumber() );
}
}