« May 2006 »
SunMonTueWedThuFriSat
    
1
2
3
4
5
6
8
9
10
11
12
13
15
17
18
20
21
23
25
26
 
       
Today
XML

Blog::Navigation

GetJava Download Button
Get the Source
Personal Blog

Blog::Referers

Today's Page Hits: 970

Powered by Roller Weblogger.
« Previous month (Apr 2006) | Main | Next month (Jun 2006) »
20060630 Friday June 30, 2006

Is this MT-safe? I think not...

I came across this article recently: A Safe Way to Stop a Java Thread. The author suggests an alternative for the deprecated Thread.stop() method. The code looks like



public class MyThread extends Thread {

    private boolean threadDone = false;

    public void done() {
        threadDone = true;
    }

    public void run() {
        while (!threadDone) {
            // work here
            // modify common data
        }
    }

}


MyThread.done() is supposed to be called by another thread that wants to stop a thread (that is running MyThread.run()). But, there is a problem here: threadDone variable is read by one thread and written by another thread. To ensure prompt communication of the stop-request, the threadDone variable must be volatile (or access to the threadDone variable must be synchronized):

    volatile private boolean threadDone = false;

Please refer to this as well: Why Are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated?



( Jun 30 2006, 09:32:51 AM IST ) Permalink Comments [3] del.icio.us | furl | simpy | slashdot | technorati | digg

20060629 Thursday June 29, 2006

From Emacs/ELisp to NetBeans/your-scripting-language?

Do you use Emacs or XEmacs (or have used it in the distant past!)? That is because it lets you to customize using Emacs Lisp? Then, you probably would be interested in this: Chuk has written A Simple Scripting Enviroment for NetBeans. This is a NetBeans module for scripting NetBeans! Currently, it supports JavaScript only -- although it uses javax.script API and hence it could be made to use any JSR-223 script engine - including Scheme!



( Jun 29 2006, 03:34:06 PM IST ) Permalink del.icio.us | furl | simpy | slashdot | technorati | digg

20060628 Wednesday June 28, 2006

intern()'ed Strings, perm. gen and jmap

I came across "All about intern()" recently. Few more facts:

  1. In Sun's JDK, internalized Strings are stored in the permanent generation and hence "compete" for space with meta-data (like, classes, methods, constant pools etc.)
  2. You may have to have increase perm. gen space using the -XX:MaxPermSize option.
  3. With Mustang (Java SE 6), the jmap tool's -permstat option prints statistics on the internalized trings (total number and size of occupied by intern'ed strings).



( Jun 28 2006, 07:25:15 PM IST ) Permalink del.icio.us | furl | simpy | slashdot | technorati | digg

20060627 Tuesday June 27, 2006

AJAX and Mustang

AJAX and Mustang

If you are reading about (and trying!) Mustang (Java SE 6), then you probably know this: Mozilla Rhino based javax.script (JSR-223) script engine is included in Mustang. And you can access Java platform API classes from JavaScript.

You may want to run JavaScript files available "out there" with Mustang's JavaScript engine (i.e., you don't want to modify/debug/test and then, use it). For example, there are many useful AJAX based scripts. The main building block of AJAX is the XMLHttpRequest constructor (and sometimes XMLSerializer and DOMParser for handling XML). I've just checked-in ajax.js to the http://scripting.dev.java.net project - this includes pure-JavaScript (well, not so pure - I call Java APIs!) implementation of XMLHttpRequest, partial implementations of XMLSerializer and DOMParser and few browser "emulating" variables (just to "fool" scripts into believing that they are running as part browser -- so that access to "window", "document" etc. work partially atleast).

What is the point?

Few use-cases for this:

  • To unit test AJAX "networking" part by "standalone" command line Java clients (or jrunscript) Because this implementation uses java.net and other Java APIs, it could be debugged by the standard Java debuggers/IDEs. Also, it is possible to instrument ajax.js for additional debugging/tracing.
  • DWR - remote objects can uniformly accessed by browser scripts and as well as rich-clients written in Java/swing. I managed to run a (simple) DWR client using ajax.js (see test.js.)
  • In Probos webcontainer, a server-side JavaScript code can call a web-service using DWR or may even directly use XMLHttpRequest.



( Jun 27 2006, 01:02:58 PM IST ) Permalink del.icio.us | furl | simpy | slashdot | technorati | digg

20060624 Saturday June 24, 2006

Using script shell plugin with jconsole

In Mustang (Java SE), jconsole has a plugin API. Plugins can extend jconsole by adding one or more tabs to the jconsole's GUI. Let us see how to use jconsole "script shell" plugin. Script shell is an interactive JavaScript shell tab within jconsole's GUI. This plugin is under the following directory:


$JDK_HOME/demo/scripting/jconsole-plugin 

I used Mustang build 89 for the following demo.

D:\jdk1.6.0\bin>java -version
java version "1.6.0-rc"
Java(TM) SE Runtime Environment (build 1.6.0-rc-b89)
Java HotSpot(TM) Client VM (build 1.6.0-rc-b89, mixed mode, sharing)

I need an application which will be monitored and managed by console. So, I start "Java2D" demo using the following command:

D:\jdk1.6.0\demo\jfc\Java2D>java -jar Java2Demo.jar

Now, I start jconsole with the following commands:

D:\>cd D:\jdk1.6.0\demo\scripting\jconsole-plugin
D:\jdk1.6.0\demo\scripting\jconsole-plugin>jconsole -pluginpath jconsole-plugin.jar

Note that I've used -pluginpath to specify the paths of jconsole plugins to be used. In the above command, I just specify script-shell plugin alone. In the jconsole's connection dialog choose the Java2D application as application to be monitored and managed. After jconsole attaches to the Java2D process, you'll see that jconsole has an additional "Script Shell" tab. When you click on that it looks like this:

As you can see, I gave few JavaScript commands and got some output from the "script shell". So far so good - usual JavaScript expressions within jconsole's GUI (yes, echo is a built-in function to display within the screen). There is nothing special about it. What is the use of this shell for monitoring and management? Let us get some help - by typing help() in the prompt...

As you can see, there are many useful "built-in" functions for accesing MBeans (like mbean, mbeanInfo, getMBeanAttribute, setMBeanAttribute, invokeMBean, newPlatformMXBeanProxy) and other utility functions (like clear, exit etc.). The built-in functions are defined in


$JDK_HOME/demo/scripting/jconsole-plugin/src/resources/jconsole.js

There is also a built-in variable by the name jcontext of type JConsoleContext. From the variable, scripts can access current jconsole context (like MBeanServerConnection)

Now let us load a few pre-written JavaScript files in the script-shell by using load built-in function.

I've loaded $JDK_HOME/demo/scripting/jconsole-plugin/src/scripts/sysprops.js file in script shell and called sysprops() function defined in that file. This function prints all Java System properties from the managed application using RuntimeMXBean. There are few more sample scripts under:


$JDK_HOME/demo/scripting/jconsole-plugin/src/scripts

jtop.js - prints threads sorted by CPU time

js>load('src/scripts/jtop.js')
js>jtop()
time - state - name 
17.75 - WAITING - AWT-EventQueue-0 
2.078125 - RUNNABLE - RMI TCP Connection(7)-127.0.0.1 
1.515625 - RUNNABLE - DestroyJavaVM 
0.46875 - RUNNABLE - AWT-Windows 
0.25 - RUNNABLE - Attach Listener 
0.234375 - TIMED_WAITING - Intro 
0.140625 - TIMED_WAITING - Image Animator 0 
0.03125 - WAITING - Reference Handler 
0.015625 - WAITING - Java2D Disposer 
0 - WAITING - Finalizer 
js>

jstack.js - prints stack traces of all Java threads


js>load('src/scripts/jstack.js')
js>jstack()
32 - RMI TCP Connection(12)-127.0.0.1 - RUNNABLE 
	java.net.SocketInputStream.socketRead0(Native Method) 
	java.net.SocketInputStream.read(SocketInputStream.java:129) 	
java.io.BufferedInputStream.fill(BufferedInputStream.java:218) 	
java.io.BufferedInputStream.read(BufferedInputStream.java:237) 
	java.io.FilterInputStream.read(FilterInputStream.java:66) 	
sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:517)
sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:790)
sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:649)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:678)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:703)
	java.lang.Thread.run(Thread.java:619)
30 - TimerQueue - WAITING 
	java.lang.Object.wait(Native Method)
	javax.swing.TimerQueue.run(TimerQueue.java:233) 
	java.lang.Thread.run(Thread.java:619)
29 - RMI TCP Connection(7)-127.0.0.1 - RUNNABLE 
	sun.management.ThreadImpl.getThreadInfo0(Native Method) 
	sun.management.ThreadImpl.getThreadInfo(ThreadImpl.java:147)
	sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 	
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	java.lang.reflect.Method.invoke(Method.java:589)
com.sun.jmx.mbeanserver.ConvertingMethod.invokeWithOpenReturn(ConvertingMethod.java:167)	
com.sun.jmx.mbeanserver.MXBeanIntrospector.invokeM2(MXBeanIntrospector.java:96)
com.sun.jmx.mbeanserver.MXBeanIntrospector.invokeM2(MXBeanIntrospector.java:33)
com.sun.jmx.mbeanserver.MBeanIntrospector.invokeM(MBeanIntrospector.java:208)
[... more output...]
js>

Note that you can access Java classes from JavaScript. Using that and the built-in variable jcontext, you can write many useful monitoring and management scripts.

For advanced users: Note that the jconsole script shell plugin uses javax.script API. It is possible to use scripting language of your choice (may be, you got JSR-223 engine for your language from http://scripting.dev.java.net) with jconsole. But, that is a topic for another blog! Or may be, you can just hack by looking at script shell sources in the demo directory!



( Jun 24 2006, 09:08:22 AM IST ) Permalink del.icio.us | furl | simpy | slashdot | technorati | digg

20060622 Thursday June 22, 2006

Foo.class does not initialize class Foo!

If you are getting Class object a class using Foo.class construct ("class literals"), the class Foo is not initialized - i.e., the static initializer of the class will not called at that point.


class Main {
  public static void main(String[] args) {
     System.out.println(Foo.class);
  }
}

class Foo {

   static {
     System.out.println("Initializing Foo..");
   }
}

When we compile and run the above Main class with JDK 1.5, we get the following output (I got this on my PC)

D:\>java -cp . Main
class Foo

We don't see "Initializing Foo.." in the output! -- because Foo.class does not initialize the class Foo. But, if we compile the classes with the command

D:\>javac -source 1.4 -target 1.4 Main.java

Now, if we run the class,

D:\>java -cp . Main
Initializing Foo..
class Foo

This time class Foo is initialized! And we get the same result with JDK 1.4.2 - i.e., if you JDK 1.4.2's javac, we see that classFoo is initialized. What is happening...??

Before 1.5, javac compiled Foo.class construct by using Class.forName(String) method:


D:\>javap -c Main
Compiled from "Main.java"
class Main extends java.lang.Object{
static java.lang.Class class$Foo;

Main();
  Code:
   0:   aload_0
   1:   invokespecial   #6; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   getstatic       #7; //Field java/lang/System.out:Ljava/io/PrintStream;
   3:   getstatic       #8; //Field class$Foo:Ljava/lang/Class;
   6:   ifnonnull       21
   9:   ldc     #9; //String Foo
   11:  invokestatic    #10; //Method class$:(Ljava/lang/String;)Ljava/lang/Class;
   14:  dup
   15:  putstatic       #8; //Field class$Foo:Ljava/lang/Class;
   18:  goto    24
   21:  getstatic       #8; //Field class$Foo:Ljava/lang/Class;
   24:  invokevirtual   #11; //Method java/io/PrintStream.println:(Ljava/lang/Object;)V
   27:  return

static java.lang.Class class$(java.lang.String);
  Code:
   0:   aload_0
   1:   invokestatic    #1; //Method java/lang/Class.forName:(Ljava/lang/String;
)Ljava/lang/Class;
   4:   areturn
   5:   astore_1
   6:   new     #3; //class java/lang/NoClassDefFoundError
   9:   dup
   10:  invokespecial   #4; //Method java/lang/NoClassDefFoundError."<init>":()V

   13:  aload_1
   14:  invokevirtual   #5; //Method java/lang/NoClassDefFoundError.initCause:(Ljava/lang/Throwable;)Ljava/lang/Throwable;
   17:  athrow
  Exception table:
   from   to  target type
     0     4     5   Class java/lang/ClassNotFoundException


}

Starting from 1.5, javac uses ldc_w instruction to compile Foo.class

D:\>javap -c Main
Compiled from "Main.java"
class Main extends java.lang.Object{
Main();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   3:   ldc_w   #3; //class Foo
   6:   invokevirtual   #4; //Method java/io/PrintStream.println:(Ljava/lang/Obj
ect;)V
   9:   return

}

The ldc_w instruction for class literals does not initialize the class. Is the behaviour of 1.5 wrong? i.e., violation of Java Language Spec? No! The language specification for initialization has not changed. It never listed class literal evaluation as an initialization trigger. Class.forName(String) method does initialize the class and therefore translating Foo.class with with Class.forName(String) resulted in the (unwanted) initialiazation of Foo. If you want the old behaviour you may want to use the workaround documented in 5.0 Compatibility notes.



( Jun 22 2006, 10:27:32 PM IST ) Permalink Comments [2] del.icio.us | furl | simpy | slashdot | technorati | digg

20060619 Monday June 19, 2006

Observability Top 10 in Mustang

You may have read Top 10 Things You Need to Know about Mustang (Java SE 6) beta-2. That top 10 covers the entire JDK. This is a Java Observability top 10:

  1. attach-on-demand API

    java.lang.instrument and JVM TI agents need not be loaded at the application start-up. Agents may be loaded "on demand".

  2. jconsole improvements

    More details: Mustang's jconsole - Mandy Chung

  3. java.util.concurrent lock information in stack traces

  4. Java heap dumps

    Java heap snapshot can be dumped into a binary format file (a.k.a hprof binary format). The format is specified http://heap-snapshot.dev.java.net There are many ways to dump the heap

    • Using -dump option with jmap against a live process
    • Running jmap against a core dump (on Solaris and Linux)
    • Running hprof profiler with -Xrunhprof:format=b option
    • Starting the JVM with -XX:+HeapDumpOnOutOfMemoryError option - with this option JVM dumps heap when OutOfMemoryError is thrown.
    • Programatically using HotSpotDiagnosticMXBean
    More Info:

  5. Heap dump analysis using jhat

    jhat - Java Heap Analysis Tool can be used to analyze the heapdumps produced by above means.

  6. DTrace Java support

  7. Turing on JVM flags dynamically

    Few JVM command line options can be turned on/off dynamically (from outside the process). Only a subset of flags - called manageable flags - can be turned on/off (or set) dynamically. Two ways:

    In addition, DTrace probes flag - ExtendedDTraceProbes flag - can also be turned on/off by jinfo

  8. New tools (with subset of options) on Windows

    • jstack (-l option and no options only, for live processes only). No mixed mode stack trace support.
    • jmap (-dump and -histo options only). i.e., heap dump and heap histogram options only.
    • jinfo (-flag and -flag +/- <flag-name> options only). i.e., only printing a JVM -XX flag value or turning on/off a JVM flag dynamically (of a live process).

  9. Better OutOfMemoryError!

    OutOfMemoryError looks a bit better! - better detail message and stack trace with OOM exception!

  10. Misc. command line tools improvements
    • jmap prints information on internalized Strings (count and total byte size) of internalized strings is printed with -permstat option
    • New -finalizerinfo option with jmap - prints summary information on objects waiting to be finalized.



( Jun 19 2006, 09:22:12 PM IST ) Permalink Comments [1] del.icio.us | furl | simpy | slashdot | technorati | digg

20060616 Friday June 16, 2006

Java heap snapshot as a database?

Mustang is now packaged with Java DB. So, we have a database included in Mustang (Java SE 6). I am excited because...

Many of you would know jmap can dump snapshot of Java heap (of a live process or a java core dump) into a binary format file. Or alternatively hprof profiler may also be used to dump heap snapshot.

The heap snapshot binary format (a.k.a hprof binary format) is described at

And you may already know that jhat (Java Heap Analysis Tool) can be used to analyze the heap dumps produced by jmap and hprof. jhat supports OQL (a SQL-like language) to query the heap.

Essential idea of jhat/OQL is this: heap snapshot is a database of objects. jhat parses the dump, creates in-memory object model, interprets query and generates result HTML.

How about this? - a new command line utility to "import" heap dump files into a database like Java DB. Then, we can use SQL to query the database - and it would be very easy to write tools on top of JDBC/SQL access. Besides, we can take advantage of the "large file" handling, indexing, query optimization aspects of the database - rather than having to implement similar stuff by jhat. Or may be, we can reimplement jhat as a tool that

  1. imports heap dump into a Java DB instance
  2. uses JDBC to query
  3. implements a web and/or swing front-end



( Jun 16 2006, 11:20:59 AM IST ) Permalink Comments [3] del.icio.us | furl | simpy | slashdot | technorati | digg

20060614 Wednesday June 14, 2006

"Dynamic source" code in Java applications

I came across "Add dynamic Java code to your application". In this (nice) article, the author discusses how to use Java compiler (javac) to generate bytecode on-the-fly and load the same using a ClassLoader. This is done to extend an application dynamically - for example, an application can check for file timestamp of .java source file and recompile/reload as needed. In the article, author proposes designing around interfaces - a Java interface used by "static" portion of the application and the implementation of the same could be dynamically generated and loaded.

With Mustang (Java SE 6), it is easy to load "dynamic" code. I'll discuss three different ways in this blog entry. In the discussion, we will implement java.lang.Runnable interface by "dynamic" code.

  1. You can use javax.script API and the JavaScript engine bundled with JRE.
    
        // method to load Runnable implementation from a script file
        public Runnable load(String file) throws Exception {
            ScriptEngineManager manager = new ScriptEngineManager();
            // get JavaScript engine instance
            ScriptEngine engine = manager.getEngineByName("JavaScript");
    
            // open the file and evaluate the code.
            // File is expected to contain a Runnable implementation
            FileReader reader = new FileReader(file);
            return (Runnable) engine.eval(reader);
        }
    
    
    The JavaScript file may contain code like
    
        new java.lang.Runnable() {
            run: function() { print("hello world"); }
        }
    
    
    More details on JavaScript-to-Java "communication" is http://www.mozilla.org/rhino/ScriptingJava.html
  2. What if you don't like to implement the interface in JavaScript and you want to use Java. What can you do? You can use the same idea discussed in the article -- but, with Mustang, you can use the standard Java Compiler API (JSR-199) instead of using non-standard com.sun.* compiler Main class.
  3. What if you want an easier way? ["Compiler API is not for me - I am a Mort neither an Elvis nor an Einstein!"]. You can download javax.script compliant script engine for the Java programming language from http://scripting.dev.java.net
    
        // method to load Runnable implementation from a Java file
        public Runnable load(String file) throws Exception {
            ScriptEngineManager manager = new ScriptEngineManager();
            // get JavaScript engine instance
            ScriptEngine engine = manager.getEngineByName("java");
    
            // open the Java source file and evaluate the code.
            // File is expected to contain a Runnable implementation
            FileReader reader = new FileReader(file);
    
            // when we evaluate a Java class, "Java" script engine
            // executes the main method and returns the Class object
            // of the "main" class from the Java source
            Class clazz = (Class) engine.eval(reader);
    
            // create a new instance of the Runnable (assumes that
            // the interface implementor class has a public no-arg
            // constructor
            return (Runnable) clazz.newInstance();
        }
    
    
    Your (dynamically loaded) Java file may contain something like:
    
    public class DynamicRunnable implements Runnable {
        public void run() {
            System.out.println("hello (dynamic) world!");
        }
    
        // dummy main method for "eval"
        public static void main(String[] args) {}
    }
    
    



( Jun 14 2006, 03:24:03 PM IST ) Permalink Comments [1] del.icio.us | furl | simpy | slashdot | technorati | digg

20060607 Wednesday June 07, 2006

Recently read in Java...

This is what I read/reading recently:

  1. Java HotSpot VM Memory Management whitepaper. Nice introduction to various GC algorithms used in HotSpot, GC command line flags and GC ergonomics, tools in particular jmap and jstat.
  2. Java(TM) Puzzlers : Traps, Pitfalls, and Corner Cases. My maneger gave me a hard copy of this book during the recent JavaOne visit to US. (Thanks!) I've been reading puzzles in random order. I like the puzzles around the differences between shadowing, obscuring, overriding and hiding and overloading.
  3. JLS, third edition - no, no! I have not read it from cover-to-cover!!

    I am neither a computational theologist nor a compiler guy. But, I do find some fun reading the "holy books" of the theologists.

    First ever programming language spec. I read is The C programming language. Then, I read The Annotated C++ Reference Manual.

    Recently, my manager gave me a hard copy of Java Language Specification Third edition as well (Thanks again!). I am not sure how far I can/will read. Usually, I refer to the online copy of JLS . For a change, I've started reading the hard copy.



( Jun 07 2006, 10:02:24 AM IST ) Permalink Comments [1] del.icio.us | furl | simpy | slashdot | technorati | digg

Copyright (C) 2005, A. Sundararajan's Weblog