Monday, October 4, 2010

Thread Helper

Thread Helper will help you to call your class method in threaded environment. It will take care all the low level complexity and provide you a simple interface to call a method in threaded environment.
To use this one should extend the class called ThreadCommand and implement the execute method of that. Whatever code will be written in execute method will be called in threaded manner.

ThreadHelper has 2 methods in it
1. Call
2. Get

Call will notify the thread helper to call the execute method of Command implementation and store the result in a map and when get method will be called, result will returned to the user and it will be removed from the map.


After call method, user can do other stuff and whenever user required the output from thread just get that from get Method. This will simulate the post evaluation mechanism. In this user first call and continue with other operation and whenever required the output just call the get method.

ThreadHelper.java


import java.util.HashMap;

import java.util.Map;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;



public class ThreadHelper

{

private boolean callWhenFetch = false;

private ExecutorService executorService = null;

private Map> futurs = null;

private boolean started = false;



/**

*

* @param callWhenFetch

*/

public ThreadHelper(boolean callWhenFetch)

{

this.callWhenFetch = callWhenFetch;

}



/**

*

*/

public ThreadHelper()

{

}



public void start()

{

executorService = Executors.newCachedThreadPool();

futurs = new HashMap>();

started = true;

}



/**

* Check if the thread Helper is Started

*

* @return

*/

public boolean isStart()

{

return started;

}



/**

* Initiates an orderly shutdown in which previously submitted commands are

* executed, but no new commands will be accepted.

*/

public void stop()

{

if (futurs != null)

{

futurs = null;

}



if (executorService != null)

{

executorService.shutdown();

}

}



/**

* Attempts to stop all actively executing commands, halts the processing of

* waiting commands

*/

public void stopNow()

{

if (futurs != null)

{

futurs = null;

}



if (executorService != null)

{

executorService.shutdownNow();

}

}



/**

* This method takes ICommand as input and submit to ThreadPool.

*

* @param command

* @throws Exception

*/

public synchronized void call(ThreadCommand command) throws Exception

{

checkIfStarted();

Future submitted = executorService.submit(command);

futurs.put(command.getId(), submitted);

}



/**

* This method give the output to previously called command. If

* callWhenFetch parameter is set to true then If you haven't call call

* method before get then it will first call call method and then call get

* of that call. If flag is set to false and you tried to call get before

* call method it will throws exception

*

* @param command

* @return

* @throws NotNotifiedException

* @throws InterruptedException

* @throws ExecutionException

*/

public T get(ThreadCommand command)

throws NotNotifiedException,

InterruptedException,

ExecutionException,

Exception

{

checkIfStarted();

Future submitted = null;

try

{

synchronized (futurs)

{



if (!futurs.containsKey(command.getId()))

{

if (!callWhenFetch)

{

throw new NotNotifiedException(

"Object is not called before get.");

}

submitted = executorService.submit(command);

futurs.put(command.getId(), submitted);

}

T object = futurs.get(command.getId()).get();

submitted = futurs.remove(command.getId());



return object;

}

}

finally

{

if (submitted != null)

{

submitted.cancel(false);

submitted = null;

}

}

}



private void checkIfStarted() throws Exception

{

if (!isStart())

{

throw new Exception(

"Please start the thread helper before using it.");

}

}



public int waitingCallCount()

{

return futurs.size();



}

}







ThreadCommand.java



import java.util.concurrent.Callable;



public abstract class ThreadCommand implements Callable

{



private String id;



public ThreadCommand(String id)

{

this.id = id;

}



public T call() throws Exception

{

return execute();

}



public String getId() {

return id;

}



public abstract T execute();



@Override

public String toString()

{

return "ThreadCommand [id=" + id + "]";

}





}




ThreadHelperTest.java



import java.util.ArrayList;

import java.util.List;



import junit.framework.TestCase;






public class ThreadHelperTest extends TestCase

{



public void testSingleThreadImmediateResponseBefoereStart()

{

try

{

ThreadCommand command = new ThreadCommand("Test")

{



@Override

public String execute()

{

// TODO Auto-generated method stub

return "I am just checking how execute is working.";

}

};



ThreadHelper helper = new ThreadHelper();

helper.call(command);

helper.get(command);

fail();

}

catch (Exception e)

{

assertEquals("Please start the thread helper before using it.", e

.getMessage());



}

}



public void testGetBeforeCallWhenCallWhenFetchIsFalse()

{

try

{

ThreadCommand command = new ThreadCommand("Test")

{



@Override

public String execute()

{

// TODO Auto-generated method stub

return "I am just checking how execute is working.";

}

};



ThreadHelper helper = new ThreadHelper(true);

//helper.call(command);

helper.get(command);

fail();

}

catch (Exception e)

{

e.printStackTrace();

assertEquals("Please start the thread helper before using it.", e

.getMessage());



}

}



public void testSingleThreadImmediateResponse()

{

try

{

ThreadCommand command = new ThreadCommand("Test")

{

public String execute()

{

return "I am just checking how execute is working.";

}

};



ThreadHelper helper = new ThreadHelper();

helper.start();

helper.call(command);

String str = helper.get(command);

assertEquals("I am just checking how execute is working.", str);



}

catch (Exception e)

{

fail();



}

}



public void testMutipleThreadImmediateResponse()

{

try

{

ThreadCommand command1 = new ThreadCommand("Test1")

{

public String execute()

{

return "[Test 1]I am just checking how execute is working.";

}

};



ThreadCommand command2 = new ThreadCommand("Test2")

{

public String execute()

{

return "[Test 2]I am just checking how execute is working.";

}

};



ThreadHelper helper = new ThreadHelper();

helper.start();

helper.call(command1);

helper.call(command2);

String str = helper.get(command2);

assertEquals(

"[Test 2]I am just checking how execute is working.",

str);

str = helper.get(command1);

assertEquals(

"[Test 1]I am just checking how execute is working.",

str);



}

catch (Exception e)

{

fail();



}

}



public void testMutipleThreadImmediateResponseForSameCommand()

{

try

{

ThreadCommand command1 = new ThreadCommand("Test1")

{

public String execute()

{

return "[Test 1]I am just checking how execute is working.";

}

};



ThreadHelper helper = new ThreadHelper();

helper.start();

helper.call(command1);

String str = helper.get(command1);

assertEquals(

"[Test 1]I am just checking how execute is working.",

str);

str = helper.get(command1);

fail();



}

catch (Exception e)

{

assertEquals("Object is not called before get.", e.getMessage());



}

}



public void testThreadHelperStatusAfterAllGet()

{

try

{

List> commands = new ArrayList>();

for (int i = 0; i < k =" i;"> command1 = new ThreadCommand(

"Test" + k)

{

public String execute()

{

return "[Test "

+ k

+ "]I am just checking how execute is working.";

}

};

commands.add(command1);

}



ThreadHelper helper = new ThreadHelper();

helper.start();

for (ThreadCommand command : commands)

{

helper.call(command);

}



assertEquals(100, helper.waitingCallCount());



// get all odd number command

for (int i = 1; i < i =" i" i =" 0;"> command : commands)

{

if(i == 100) {

break;

}

assertEquals("[Test "

+ i

+ "]I am just checking how execute is working.", helper

.get(commands.get(i)));

i = i + 2;



}

// get rest of the commands

assertEquals(0, helper.waitingCallCount());



}

catch (Exception e)

{

e.printStackTrace();

fail();



}

}

}

Tuesday, September 28, 2010

Eclipse Memory Analyzer

http://wiki.eclipse.org/index.php/MemoryAnalyzer

I will post the details soon

XLogger

Last few days I was looking to improve the logger. Main issue with the logger that we need to make sure we are using log.isXXXEnabled() for all log calls. So we are making sure that in the log message we are not making unnecessary string if logger is not going to print that. Also sometime we do perfLogger with System.currentTimeInMillis but we actually not using in prod server, but this system call are very time consuming. I was thinking of how to improve it so i have come up with customize logger called XLogger.

XLogger.java

import java.text.MessageFormat;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.Priority;
/**
*
* XLogger is wrapper around the Logger provided by apache.
* This framework will make sure that you are not building a string for
* log until it is not candidate for logging. Logger has provided isXXXEnable method
* to do this but for every logging statement, using this is tedious.
*
* It is also helpful for performance logging.
* @author Viren.Balaut
*
*/
public class XLogger
{
private Logger logger = null;
private boolean isPerfLogger = false;
private long startTime = -1;
private long endTime = -1;
public static XLogger getLogger()
{
return new XLogger(false);
}
public static XLogger getLogger(String name)
{
return new XLogger(name, false);
}
public static XLogger getLogger(Class clazz)
{
return new XLogger(clazz, false);
}
public static XLogger getPerfLogger()
{
return new XLogger(true);
}
public static XLogger getPerfLogger(String name)
{
return new XLogger(name, true);
}
public static XLogger getPerfLogger(Class clazz)
{
return new XLogger(clazz, true);
}
private XLogger(boolean isPerfLogger)
{
logger = LogManager.getRootLogger();
this.isPerfLogger = isPerfLogger;
}
private XLogger(String name, boolean isPerfLogger)
{
logger = LogManager.getLogger(name);
this.isPerfLogger = isPerfLogger;
}
private XLogger(Class clazz, boolean isPerfLogger)
{
logger = LogManager.getLogger(clazz);
this.isPerfLogger = isPerfLogger;
}
public void start()
{
if (logger.isDebugEnabled() && isPerfLogger)
{
startTime = System.currentTimeMillis();
}
}
public void stop()
{
if (logger.isDebugEnabled() && isPerfLogger)
{
if (startTime <= -1)
{
throw new IllegalStateException(
"Please call start() before calling end.");
}
endTime = System.currentTimeMillis();
}
}
public void perf(String message, String methodName)
{
if (logger.isDebugEnabled() && isPerfLogger)
{
if (startTime <= -1 endTime <= -1)
{
throw new IllegalStateException(
"Please call start() and end() both before calling logPerf.");
}
debug(
message + ", Time taken({0}) in MS : {1}",
methodName,
(endTime - startTime));
resetTimer();
}
}
public void console(String message, Object... objects)
{
System.err.println(getMessage(message, objects));
}
public void debug(String message, Object... objects)
{
if (logger.isDebugEnabled())
{
logger.debug(getMessage(message, objects));
}
}
public void info(String message, Object... objects)
{
if (logger.isInfoEnabled())
{
logger.info(getMessage(message, objects));
}
}
public void warn(String message, Object... objects)
{
if (logger.isEnabledFor(Priority.WARN))
{
logger.warn(getMessage(message, objects));
}
}
public void error(String message, Object... objects)
{
if (logger.isEnabledFor(Priority.ERROR))
{
logger.error(getMessage(message, objects));
}
}
public void error(String message, Throwable e, Object... objects)
{
if (logger.isEnabledFor(Priority.ERROR))
{
logger.error(getMessage(message, objects), e);
}
}
public void fatel(String message, Throwable e, Object... objects)
{
if (logger.isEnabledFor(Priority.FATAL))
{
logger.fatal(getMessage(message, objects), e);
}
}
private String getMessage(String message, Object... objects)
{
try
{
MessageFormat form = new MessageFormat(message);
String msg = form.format(objects);
return msg;
}
catch (Exception e)
{
System.err.println("Error occurred while parsing message for "
+ message);
return message;
}
}
private void resetTimer()
{
startTime = -1;
endTime = -1;
}
}

Monday, September 27, 2010

Resource Handling

Resource Handling
In Java, Most of the time we open some resource and after using we forget to close the resource and that make a lots of open connection for the resouse if we are not using a good ConnectionPool for resource. Still if we are using the connectino pool, then also we need to release the resopuse after use, so other can use that resource for their operation.
here is sample framework which basically takes care of these part in your java program.

Here I have two classes, one is TransactionGuard and other is Command interface.

TransactionGuard.java

/**
* TransactionGuard is make sure you release the particular resource after use.
* By using any resource, it will make sure that you are closing the resource
* after using. To use this one need to implement getConnection and
* releaseConnection method based on the need.
*
* @author Virendra.Balaut
*
* @param
* an element/resource for which you want to implement
* TransactionGuard
*/
public abstract class TransactionGuard
{
/**
* This is the main execute method which takes care of getting a connection of T type,
* do some operation and after use close the connection.
*
* @param command
* @throws Exception
*/
public void execute(Command command) throws Exception
{
T connection = null;
try
{
connection = getConnection();
command.execute(connection);
}
finally
{
releaseConnection(connection);
}

}

/**
* Abstract method to get Connection for a dedicated Type.
*
* @return
*/
protected abstract T getConnection() throws Exception;

/**
* Abstract method to release connection for a dedicated type.
*
* @param connection
*/
protected abstract void releaseConnection(T connection) throws Exception;
}


Command.java


public abstract class Command
{
public abstract void execute();
}

Using these framework will ensure that resouce will automatically closed after use.

Sample Example :-

Here I have sample program which will do database operation. So I need to open a database connection and after use it I need to release that connection.

new TransactionGuard()
{

@Override
protected Connection getConnection() throws Exception
{
Connection connection = createConnection();
return connection;
}

@Override
protected void releaseConnection(Connection connection)
throws Exception
{
if(connection != null) {
connection.close();
}

}
}.execute(new Command()
{

public void execute(Connection connection) throws Exception
{
// Do some operation with connection.

}
});


Let me know your suggestions/views.

Thursday, October 18, 2007

Generics (A Compile-Time Protection)

All the generic code is strictly for the compiler. Through a process called "type erasure," the compiler does all of its verifications on your generic code and then strips the type information out of the class bytecode. None of your typing information exists at runtime.
In other words, even though you write
List myList = new ArrayList();


By the time the compiler is done with it, the JVM sees what it always saw before Java 5 and generics:
List myList = new ArrayList();

The compiler even inserts the casts for you—the casts you had to do to get things out of a pre-Java 5 collection. Think of generics as strictly a compile-time protection. The compiler uses generic type information (the in the angle brackets) to make sure that your code doesn't put the wrong things into a collection, and that you do not assign what you get from a collection to the wrong reference type. But NONE of this protection exists at runtime.

public class GenericTest
{
public static void main(String[] args)
{
List list1 = new ArrayList();
list1.add(7);
list1.add(16);
NonGeneric ng = new NonGeneric ();
ng.insert(list1);
System.out.println(list1);
}
}

class NonGeneric
{
void insert(List list)
{
list.add("hello");
}
}

Above code will compile and run without errors. Output will be
[7, 16, hello]

Improving Code Quality with PMD and Eclipse

PMD is a static code analyzer for Java. Developers use PMD to comply with coding standards and deliver quality code. Team leaders and Quality Assurance folks use it to change the nature of code reviews. PMD has the potential to transform a mechanical and syntax check oriented code review into a to dynamic peer-to-peer discussion.

What is PMD?
PMD works by scanning Java code and checks for violations in three major areas:

Compliance with coding standards such as:


Naming conventions - class, method, parameter and variable names
Class and method length
Existence and formatting of comments and JavaDocs
Coding antipatterns such as:

Empty try/catch/finally/switch blocks
Unused local variables, parameters and private methods
Empty if/while statements
Overcomplicated expressions - unnecessary if statements, for loops that could be while loops
Classes with high Cyclomatic Complexity measurements
Cut and Paste Detector (CPD) - a tool that scans files and looks for suspect code replication. CPD can be parameterized by the minimum size of the code block.
In its current version, PMD comes packaged with 149 rules in 19 rulesets. Most of these rules can be parameterized at runtime by supplying properties or parameters. The standard package offers many well-thought rules. In addition users also have the ability to add their own rules for particular coding convention or quality metrics.

Here are some of the rules distributed with PMD:

EmptyFinalizer - If the finalize() method is empty, then it does not need to exist.
EmptyFinallyBlock - Avoid empty finally blocks - these can be deleted.
UnnecessaryReturn - Avoid unnecessary return statements
OnlyOneReturn - A method should have only one exit point, and that should be the last statement in the method.
CyclomaticComplexity - Complexity is determined by the number of decision points in a method plus one for the method entry. The decision points are 'if', 'while', 'for', and 'case labels'. Generally, 1-4 is low complexity, 5-7 indicates moderate complexity, 8-10 is high complexity, and 11+ is very high complexity.
TooManyFields - Classes that have too many fields could be redesigned to have fewer fields, possibly through some nested object grouping of some of the information. For example, a class with city/state/zip fields could instead have one Address field.
LongVariable - Detects when a field, formal or local variable is declared with a long name.
NoPackage - Detects when a class or interface does not have a package definition

Compiling code in Eclipse

One of the best features of Eclipse is that it does not use the standard java compiler (javac.exe) which comes as part of the JDK. Eclipse instead comes bundled with

it's own compiler, which allows you to configure it in many interesting ways.For e.g. Some of the things you can do at compile time are as follows Report an error/warning for missing javadocs on public methods. Report an error/warning for malformed/incorrectly written javadocs.Report an error/warning for undocumented empty blocks.Report an error/warning for unused import statement.Report an error/warning for access to a null pointer.etc

All these settings can be configured by the settings under

Preferences -> Java -> Compiler.

Many of these settings are set to 'ignore' by default.

If set appropriately, Eclipse by itself can improve the quality of code which we write.