Archive for the Java Category

SwingWorker not on Java 6.0

Posted in Java, Programming with tags , on April 24, 2008 by wsjoung

SwingWorker is useful when a time-consuming task has to be performed following a user-interaction event (for example, parsing a huge XML File, on pressing a Button). The most straightforward way to do it is :

 private Document doc;
 JButton button = new JButton("Open XML");
 button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
       doc = loadXML();

This will work, but unfortunately, the loadXML() method will be called in the same thread as the main Swing thread, so if the method needs time to perform, the GUI will freeze during this time.

package com.wsjoung.demo;
import javax.swing.SwingUtilities;

public abstract class SwingWorker {
    // see getValue(), setValue()
    private Object value;
    private Thread thread;

    private static class ThreadVar {
        private Thread thread;
        ThreadVar(Thread t) { thread = t; }
        synchronized Thread get() { return thread; }
        synchronized void clear() { thread = null; }

    private ThreadVar threadVar;

    protected synchronized Object getValue() {
        return value;

    private synchronized void setValue(Object x) {
        value = x;

    public abstract Object construct();

    public void finished() {

    public void interrupt() {
        Thread t = threadVar.get();
        if (t != null) {

    public Object get() {
        while (true) {
            Thread t = threadVar.get();
            if (t == null) {
                return getValue();
            try {
            catch (InterruptedException e) {
                // propagate
                return null;

    public SwingWorker() {
        final Runnable doFinished = new Runnable() {
           public void run() { finished(); }

        Runnable doConstruct = new Runnable() {
            public void run() {
                try {
                finally {


        Thread t = new Thread(doConstruct);
        threadVar = new ThreadVar(t);

public class Task{
  public void go() {
      current = 0;
      final SwingWorker worker = new SwingWorker() {
          public Object construct() {
              return new ActualTask();

  class ActualTask {
      ActualTask() {
          try {
          } catch (InterruptedException e) {}

Java SE 6 Key Features

Posted in Java with tags , on December 13, 2006 by wsjoung

New Security Features and Enhancements

  • Native platform Security (GSS/Kerberos) integration.
  • Java Authentication and Authorization Service (JAAS) login module that employs LDAP authentication
  • New Smart Card I/O API
    » Find out more

Integrated Web Services

  • New API for XML digital signature services for secure web services
  • New Client and Core Java Architecture for XML-Web Services (JAX-WS) 2.0 APIs
  • New support for Java Architecture for XML Binding (JAXB) 2.0
    » Find out more

Scripting Language Support (JSR 223)

  • New framework and API for scripting languages
  • Mozilla Rhino engine for JavaScript built into the platform
    » Find out more

Enhanced Management and Serviceability

  • Improved JMX Monitoring API
  • Runtime Support for dTrace (Solaris 10 and future Solaris OS releases only)
  • Improved memory usage analysis and leak detection
    » Find out more

Increased Developer Productivity

  • JDBC 4.0 support (JSR 221)
  • Significant library improvements
  • Improvements to the Java Platform Debug Architecture (JPDA) & JVM Tool Interface

Improved User Experience

  • look-and-feel updates to better match underlying operating system
  • Improved desktop performance and integration
  • Enhanced internationalization support

“null”, is this Object or not?

Posted in Java with tags , , on November 26, 2006 by wsjoung

In java, some people say null is Object and they also use “null object” term when they try to explain something related in null like NullPointerException.

And some people simply show “null instanceof Object” result to prove that null is not Object. Of course it returns false for “null instanceof Object”. Because null is technically not Object.

The reason why people keep regarding null as a kind of Object is that they are confused those two terms, Object itself and Reference variable which points an object. Whenever they say “null object”, which means actually reference variable, and that reference variable assigned for a specific bit pattern which is for null.

The Java Virtual Machine Tool Interface (JVMTI)

Posted in Java with tags , on November 17, 2006 by wsjoung

JVMTI is a new native interface available in J2SDK1.5.0. JVMPI is still also available though, SUN plan to drop JVMPI soon or later.

“JVMTI provides for all the functional capabilities of the previous native interfaces JVMDI and JVMPI. However, it does not have many of the limitations of those older interfaces. Some of the JVMPI capabilities require the use of JVMTI and the technique called Byte Code Insertion (BCI), sometimes referred to as Byte Code Injection or Byte Code Instrumentation. JVMTI allows for all JVM functionality to continue to operate, like JIT or JVM compilation and different GC implementations. Certain JVMTI features are controlled by asking for JVMTI Capabilities, and some of these can cause changes in JVM performance, but most features are available while the JVM is running “full speed”. All JVMTI object handles are JNI handles, and JVMTI Event callbacks always include a JNIEnv* argument to facilitate JNI usage. Multiple JVMTI agents can operate in a single JVM and all interfaces return an error code to determine success or failure of the request. It is the intention of JVMTI to displace both JVMPI and JVMDI, and to ultimately be the single native tool interface into the JVM. ” The JVMPI Transition to JVMTI

There is my sample code.


#include “jvmti.h”

static jvmtiEnv *jvmti = NULL;
static jvmtiCapabilities capa;

//****** Implementation from here ******//

static void
check_jvmti_error(jvmtiEnv *jvmti, jvmtiError errnum, const char *str)
if ( errnum != JVMTI_ERROR_NONE ) {
char *errnum_str;

errnum_str = NULL;
(void)(*jvmti)->GetErrorName(jvmti, errnum, &errnum_str);

printf(“ERROR: JVMTI: %d(%s): %s\n”, errnum, (errnum_str==NULL?”Unknown”:errnum_str), (str==NULL?””:str));

static void JNICALL
callbackVMInit(jvmtiEnv *jvmti_env, JNIEnv* jni_env, jthread thread)
printf(“JVMTI_EVENT_VM_INIT is captured\n”);

static void
JNICALL callbackVMDeath(jvmtiEnv *jvmti_env, JNIEnv* jni_env)
printf(“JVMTI_EVENT_VM_DEATH is captured\n”);

static void JNICALL
callbackVMObjectAlloc(jvmtiEnv *jvmti_env, JNIEnv* jni_env, jthread thread, jobject object, jclass object_klass, jlong size)
printf(“JVMTI_EVENT_VM_OBJECT_ALLOC is captured:\n”);

/* Agent_OnLoad() is called first, we prepare for a VM_INIT event here. */
Agent_OnLoad(JavaVM *jvm, char *options, void *reserved)

jint res;
jvmtiEventCallbacks callbacks;
jvmtiError error;

res = (*jvm)->GetEnv(jvm, (void **) &jvmti, JVMTI_VERSION);

if (res != JNI_OK || jvmti == NULL) {
/* This means that the VM was unable to obtain this version of the
* JVMTI interface, this is a fatal error.
printf(“ERROR: Unable to access JVMTI Version 1 (0x%x),”
” is your J2SE a 1.5 or newer version?”
” JNIEnv’s GetEnv() returned %d\n”,


memset(&capa, 0, sizeof(jvmtiCapabilities));
error = (*jvmti)->GetPotentialCapabilities(jvmti, &capa);
if (error == JVMTI_ERROR_NONE) {
error = (*jvmti)->AddCapabilities(jvmti, &capa);
check_jvmti_error(jvmti, error, “Unable to get necessary JVMTI capabilities.”);

memset(&callbacks, 0, sizeof(callbacks));
callbacks.VMInit = &callbackVMInit; /* JVMTI_EVENT_VM_INIT */
callbacks.VMDeath = &callbackVMDeath; /* JVMTI_EVENT_VM_DEATH */
callbacks.VMObjectAlloc = &callbackVMObjectAlloc;/* JVMTI_EVENT_VM_OBJECT_ALLOC */

error = (*jvmti)->SetEventCallbacks(jvmti, &callbacks, (jint)sizeof(callbacks));
check_jvmti_error(jvmti, error, “Cannot set jvmti callbacks”);

error = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, (jthread)NULL);
error = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, JVMTI_EVENT_VM_DEATH, (jthread)NULL);
error = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, JVMTI_EVENT_VM_OBJECT_ALLOC, (jthread)NULL);
check_jvmti_error(jvmti, error, “Cannot set event notification”);

return JNI_OK;


/* Agent_OnUnload() is called last */
Agent_OnUnload(JavaVM *vm)

JVMTI Reference

Java memory management

Posted in Java with tags , on November 17, 2006 by wsjoung

JVM with the -verbose:gc or -Xloggc:
a diagnostic message is printed on the console or to a log file every time the GC runs, including how long it took, the current heap usage, and how much memory was recovered. Logging GC usage is not intrusive, and so it is reasonable to enable GC logging in production by default in the event you ever need to analyze memory problems or tune the garbage collector.

JVM with the -Xrunhprof[:suboption=value]
Enables cpu, heap, or monitor profiling.
java -Xrunhprof:help to obtain a list of suboptions and their default values.

GC Portal
The GC Portal enables analysis and performance tuning of Java applications from a garbage collection (GC) perspective by mining the verbose:gc logs generated by the JVM.

HPjtune is a Java Garbage Collection visualization tool for analyzing garbage collection activity in a Java program. The analysis is carried out off-line or on-line, based on the output of the JVM via the -Xloggc or -Xverbosegc output file.

JavaTM HotSpot VM Options

Java Feature, Graph3D

Posted in Java with tags , on May 27, 2006 by wsjoung

My current research obviously need to handle 3D graph. actually it just a graph. basically I need to compare those 3D images then I should choose the most common one. I am still working on it.

I hope that this Java 3D features are good for my work.

Java Feature — Graph3D In today’s work environment analyzing large amounts of varying data types is paramount. Graphing techniques can be an invaluable tool to understanding and interpreting that data. In many cases two-dimensional graphs, such as XY, scatter, pie, and bar charts, are sufficient. But increasingly more complex graphing techniques are needed. In these instances Java3D is an excellent resource with numerous features that allow personalized generation of three-dimensional data displays. Not only will Java3D yield better insight into the data by highlighting important aspects of the data, but it also makes attractive displays to spice up any presentation.