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?
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!
I came across "All about intern()" recently. Few more facts:
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).
Few use-cases for this:
ajax.js for additional debugging/tracing.
ajax.js (see test.js.)
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!
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.
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:
java.lang.instrument and JVM TI agents need not be loaded at the application start-up. Agents may be loaded "on demand".
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
jhat - Java Heap Analysis Tool can be used to analyze the heapdumps produced by above means.
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:
OutOfMemoryError looks a bit better! - better detail message and stack trace with OOM exception!
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
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.
// 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
// 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) {}
}
This is what I read/reading recently:
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.