Monday, September 13, 2010

Using Java SignalHandling and ShutDownHook

  • Singal Handling

Here I only briefly talk about the the Java Signal handling under Unix/Linux using Sun's implementation; In Sun's implementation, there is an interface SingleHandler and a Single class, they are located in rt.jar file,for every signal you want to capure, you need create a corresponding instance for it, and then register it into the Singal's handlers:

1. Singal signal = new Signal( TERM );

2. YourSignalHandler youHandler = new YourSignalHandler();

3. Singal.handle( singal, youHandler);

Then your handler is ready to handle signals, you may use kill -TERM processId to send signal to your signal handler.

When you use singal handling with JVM, you need consider some signals have already been listened by the JVM, and signals can only be handled by one handler, if you want to handle it, you must tell JVM to ignore it using -Xrs option when you bring up the JVM( Sun JVM)

  • Shudown hook

Sometime, you want to do some cleanup when your application is shuting down, for example, shutdown your thread pool, close your connection pool and close files gracefully.

1. Shutdown hook is a class which extends Thread class, and can be installed using Runtime.getRuntime().addShutdownHook() or removed using Runtime.getRuntime().removeShutdownHook()

2. Each shudown hook will be started when the JVM terminating, and they are running simultaneously, so synchronization should be considered if ncessary.

3. Shudown hook will be invoked under the following scenarios:

  • Application normal exits, for example, calling System.exit(0), Runtime.exit(), or the last non-deamon thread exits
  • JVM is terminated by some signals, such as SIGTERM, SIGHUP, etc.

4. Shutdown hook will not be invoked when:

  • JVM Crash
  • Runtime.halt() is called.
  • JVM -Xrs option is specified when bring up the JVM

In my previous post, I have talked about how to break the blocking I/O, especailly about how to gracefully shutdown the listener, now we know we could put the serverSocket.close() into a shudown hook, and then user sends a SIGTERM signal to the JVM, the JVM will be terminated and invoke the shudown hook to close the server socket. When the shutdown hook(s) are executed, the JVM will wait until all shutdown hooks finish their job, so you must make sure all of your shutdown hook finish their jobs properly, otherwise the JVM will hung.

For more detailed information about shutdown hook and signal handling, please refer to :

Revelations on Java signal handling and termination

 

Posted via email from Progress

A few simple ways to break your blocking I/O operatio

Tranditional blocking I/O is not like Thread.sleep(), Object.wait(), Thread.join(), etc, it cannot interrupted by the Thread.interrupt() method, but the others list above could be interrupted and you will get InterruptedException.

In blocking I/O, such as ServerSocket.accept(), if no more connect requests coming, it will be blocked maybe for ever. If you create a listern listening on a port, but you want to shutdown it gracefully, you may choose the following ways to do that:

1. Create a client socket and call connect() to this listener's port:

        Socket client = new Socket();
        try {
            client.connect(new InetSocketAddress(this.IP, this.port));
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    This will make the ServerSocket.accept() break, and make the thread proceeds.

2. Keep a reference( i.e serverSocket) to the ServerSocket you created in the listener, later when you want to shutdown the listener, just call serverSocket.close(), this also break the ServerSocket.accept().

3. The third way is not so graceful, but if you don't care about what is runing, it works, just uses kill -9 to kill the process.

Posted via email from Progress

Friday, September 10, 2010

Print Java class/method name, line number in your log file

Sometime it's very helpful to print verbose information in the log file, of course it will have impact on your performance.

Get class name is very easy, but dynamically get the method name and line number at the point you put your log message need you get help from Throwable class,

When we call new Throwable(), in the constructor, it first call fillInStackTrace() method, after the object is created, we could call throwable.getStackTrace() which returns an array of StackTraceElement, StackTraceElement[0] will be the method which creates the Throwable() object, StackTraceElement[1] will be the one outside the preivous mehtod, and so on. For exampe:

Wednesday, September 8, 2010

Use of ThreadLocal class

ThreadLocal helps to maintain a separate copy of the value for each thread that use it, it is often used to prevent sharing in designs based on mutable Singletons or global variables.
Conceptually, you can think of a ThreadLocal as holding a Map that stores the thread specific values, but the real implementation is not this way, the read data actually stored in the Thread object itself.

In Thread class, there are two private variables:
ThreadLocal.Values localValues;
ThreadLocal.Values inheritableValues;

Here is how the real per-thread values are stored. (ThreadLocal.set()):

public void set(T value) {
Thread currentThread = Thread.currentThread();
Values values = values(currentThread);
if (values == null) {
values = initializeValues(currentThread);
}
values.put(this, value);
}

Values values(Thread current) {
return current.localValues;
}

Values initializeValues(Thread current) {
return current.localValues = new Values();
}

From the above code, we may see that ThreadLocal set values into Thread object's
localValues variable.When the thread terminates, the thread-specific values can be GCed.

For details please see:
crazybob.org: Hard Core Java: ThreadLocal


Improve your Java code performance

1. JDK 1.5 and above provide some new features to replace some old implementations:

  • StringBuilder is a replacement of StringBuffer

StringBuffer instances are almost always used by a single thread,yet they perform

internal synchronization. It is for this reason that was essentially replaced by StringBuilder,

which is an unsynchronized

  • Vector and ArrayList, if you create and modify the Vector within a method, ArrayList

will have better performance

2. If you only need read data from a collection, Collections.unmodifiable() will return the read-only view of

the passed in colleciton, you don't need to create a copy of the data, and you will consume less memory,

make less impact on garbage collector, and make the program faster.

Posted via email from Progress