Java Application – Make sure only single/one instance running – with File Lock and ShutdownHook Monday, Jul 21 2008 

Often we want to make sure that only 1 instance our application running.
Because something terrible could happen when more than 1 instance running (for example the whole server would exploded and that would make you fired ๐Ÿ˜‰ )

Nevertheless what the reason, one of the way to make this happen is by creating a lock file as a sign that an instance is currently running.
So you application will have this flow:

  1. Check if the lock file exists.
  2. Try to delete the lock file to check if there’s really a running process lock the file.
  3. Get the file lock.
  4. If failed to get the lock file, show error that there’s already an instance running –> the end
  5. If successfully get the lock then go on with your application want to do.
  6. When application ended/closed release the lock and delete the file lock.

package test.jimmy.filelock;

import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class MyApp {

    private static File f;
    private static FileChannel channel;
    private static FileLock lock;

    public static void main(String[] args) {
        try {
            f = new File("RingOnRequest.lock");
            // Check if the lock exist
            if (f.exists()) {
                // if exist try to delete it
            // Try to get the lock
            channel = new RandomAccessFile(f, "rw").getChannel();
            lock = channel.tryLock();
            if(lock == null)
                // File is lock by other application
                throw new RuntimeException("Only 1 instance of MyApp can run.");
            // Add shutdown hook to release lock when application shutdown
            ShutdownHook shutdownHook = new ShutdownHook();

            //Your application tasks here..
            try {
            } catch (InterruptedException e) {

        catch(IOException e)
            throw new RuntimeException("Could not start process.", e);


    public static void unlockFile() {
        // release and delete file lock
        try {
            if(lock != null) {
        } catch(IOException e) {

    static class ShutdownHook extends Thread {

        public void run() {


Technorati Tags: , , , , , ,


Using mock object with jmock 2 Wednesday, Dec 26 2007 

Okay, finally you decide it’s time to create a unit testing for your project (after a long ad hoc programming life :p).
When you create a sample unit testing, it’s all seem so simple.. you fascinate by the junit easiness, how it can do reflection and make it simple.

When you want to create a real unit testing for your project, you realize that a ‘real’ method is not like just adding 2 int argument and return a result. It’s more complex and using interface as parameter is common…
Now a thought cross your mind “do I have to create all stupid classes to implement all the interface I need?”, you starting to think that creating unit testing is really waste of time & you don’t want to do it anymore :p

It’s time mock object framework come to rescue… before you fall to the darkness of untested code ๐Ÿ™‚
There’re several mock object framework like jMock, easymock, etc

Here’s an example creatin HttpMethod mock-object with jMock 2 & JUnit 3

public class sampleJMockTest extends MockObjectTestCase {
  public void testCreateHTTPMethod() {
    final HttpMethod httpMethod = mock(HttpMethod.class);
    checking(new Expectations() {
      will(returnValue("sample response"));
    SomeObject someObject = new SomeObject();

This sample will create an instance of HttpMethod (which is an interface) and when this mock object’s ‘getResponseBodyAsString’ method called it’ll return “sample response”.
So now we can easily create all interface implementation we need.Of course there’re more in jMock than just this simple feature, check it more at jMock Cookbook

Simple Log4J implementation Thursday, Nov 15 2007 

Why do we need a library for logger? doesn’t System.out.println help us enough?
When you try log4j you wouldn’t use System.out.println ever again… (Ok.. you will still used it.. occasionally :p)

What do you need? of course you need to download log4j first ๐Ÿ˜‰ , get it at log4j download page
And open your favorite Java IDE.

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
* @author jimmy
public class SampleLog4j {

private final static Logger LOGGER = Logger.getLogger(SampleLog4j.class);

public static void main(String[] args) {
LOGGER.trace(“Level trace”);
LOGGER.debug(“Level debug”);“Level info”);
LOGGER.warn(“Level warn”);
LOGGER.fatal(“Level fatal”);


This program will read file in the folder for log4j configuration.
Example of

### file appender
log4j.appender.file.layout.ConversionPattern=%d{ISO8601} — %p %C(%M):%L — %m%n
### console appender
log4j.appender.console.layout.ConversionPattern=%d{ISO8601} — %p %C(%M):%L — %m%nlog4j.rootLogger=debug, console
# uncomment the line below if you want log output to file
# log4j.rootLogger=debug, file

And it’ll produce output:

2007-11-15 18:19:09,812 — DEBUG testing.SampleLog4j(main):26 — Level debug
2007-11-15 18:19:09,828 — INFO testing.SampleLog4j(main):27 — Level info
2007-11-15 18:19:09,828 — WARN testing.SampleLog4j(main):28 — Level warn
2007-11-15 18:19:09,828 — FATAL testing.SampleLog4j(main):29 — Level fatal

Why the log “Level trace” doesn’t logged, because we set the log level only to debug.
You should learn the configuration. There are 2 appender, 1 will log to console and other will log to a file.

Now why shouldn’t I used standard System.out.println?

  • You can’t set the level of log with println only
  • You will end up delete/comment the log using println
  • It won’t be that easy to create log to file with different filename daily (daily-rolling)
  • I wonder how your println can print class name, line number easily ๐Ÿ™‚
  • … you can add more after you try it ๐Ÿ˜‰

Java Constant Pool : String Friday, Aug 10 2007 

For those who already experienced in Java Programming should already familiar with the concept of String constant pool.

String s1 = “jim”;
String s2 = “jim”;

System.out.println(s1==s2); // true.

Object s2 is the same object with s1. But if you create using new operator:

String s1 = “jim”;
String s2 = new String(“jim”);
System.out.println(s1==s2); //false.

It will allocate new Object instead getting from String constant pool.
Another sample:

String s1 = “jim”;
String s2 = “j”+”im”;
String s3 = “j”;
String im = “im”;
s3+= im;
System.out.println(s1==s2); //true.
System.out.println(s1==s3); //false.

Concatenation during runtime will create new String Object.
Sample if using final modifier:

final String s1 = “j”;
final String s2 = “im”;
String jim = “jim”;
System.out.println(s1+s2 == jim); // returns true: Constant expression.

String s3 = “j”;
String s4 = “im”;
System.out.println(s3 + s4 == jim); // returns false: Not a constant expression.

Concatenation of 2 final String is a Constant.

Although is not necessary for us programmer to know about the detail of JVM implementation about String Constant Pool. Some would say “I’m not stupid, I used equals to check equality of Strings. And I don’t really care how JVM in my OS implemented the damn Constant Pool”. But for me knowing this knowledge is something great, and somehow I think it will help me in the future ๐Ÿ™‚

More information about this : JLS – Lexical Structure

  • Literal strings within the same class (ยง8) in the same package (ยง7) represent references to the same String object (ยง4.3.1).
  • Literal strings within different classes in the same package represent references to the same String object.
  • Literal strings within different classes in different packages likewise represent references to the same String object.
  • Strings computed by constant expressions (ยง15.28) are computed at compile time and then treated as if they were literals.
  • Strings computed by concatenation at run time are newly created and therefore distinct.