Thursday, July 5, 2012

URLClassLoader and reloading a class from the web example


Reload jar from remote example
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

public class UrlJarReloader {

public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
while (true) {
reloadJarFile();
}
}

private void reloadJarFile() {
try {
System.out.println(" -- Reloading the jar file from the web !");
   String classToLoad = "org.apache.commons.lang3.StringUtils";

   URL jarUrl = new URL("jar:http://archiva/archiva/repository/internal/org/apache/commons/commons-lang3/3.1/commons-lang3-3.1.jar!/");
   URLClassLoader cl = new URLClassLoader(new URL[] {jarUrl}, null);
   Class loadedClass = cl.loadClass(classToLoad);
   
   Method method = loadedClass.getMethod("trim", new Class[] {java.lang.String.class});
   Object reloadMe = loadedClass.getConstructor().newInstance();
   String trimmedString = (String) method.invoke(reloadMe, new Object[]{"           1 2 3 4 5 6          "});
System.out.println(" -- Trimmed string is : {" + trimmedString + "}");
} catch (Exception e) {
e.printStackTrace();
}
}
};
startReloader(r);
}

private static void startReloader(Runnable r) {
try {
Thread reloader = new Thread(r);
reloader.start();
reloader.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Tuesday, July 3, 2012

Hot Deploy Example

Can be used to build a generic task-execution engine that can be used to load the code supplied by any remote client.


The most important point is to correctly set the parent class loader which is null here .
note: with windows custom urlClassLoader is necessary which is overrides the close method of the base class  (due to a jvm bug{may be fixed in jdk7})


import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;


import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;


public class JarReloader {


public static void main(String[] args) {

Runnable r = new Runnable() {

@Override
public void run() {
while (true) {
reloadJarFile();
watchDirectory();
}
}


private void reloadJarFile() {
try {
System.out.println("Reloading the jar file !");
URLClassLoader cl = null;
   File file = new File("/home/ssunel/jars/reload.jar");
   String classToLoad = "com.freetime.enjoy.ReloadMe";
   URL jarUrl = new URL("file:" + file.getAbsolutePath());
   cl = new URLClassLoader(new URL[] {jarUrl}, null);
   Class loadedClass = cl.loadClass(classToLoad);
   Method method = loadedClass.getMethod("giveAMessage", new Class[] {});
   Object reloadMe = loadedClass.getConstructor().newInstance();
   method.invoke(reloadMe, null);
} catch (Exception e) {
e.printStackTrace();
}
}


private void watchDirectory() {
try {
Path dir = Paths.get("/home/ssunel/jars");
WatchService watchService = FileSystems.getDefault().newWatchService();
dir.register(watchService, ENTRY_CREATE, ENTRY_MODIFY);
WatchKey watchKey = watchService.take();
for (WatchEvent<?> event : watchKey.pollEvents()) {
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path name = ev.context();
Path child = dir.resolve(name);
System.out.format("%s: %s\n", event.kind().name(), child);
}
Thread.sleep(1000L);
       } catch (Exception x) {
           return;
       }
}


};

startReloader(r);

}


private static void startReloader(Runnable r) {
try {
Thread reloader = new Thread(r);
reloader.start();
reloader.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}


package com.freetime.enjoy;

public class ReloadMe {
private final static String someMessage = "HELLO WORLD AGAIN";
public static void giveAMessage (){
System.out.println(someMessage);
}
}

Directory Change Listener Example


jdk 7 Watch Service Sample Usage
The java.nio.file package provides a file change notification API, called the Watch Service API. This API enables you to register a directory (or directories) with the watch service. When registering, you tell the service which types of events you are interested in: file creation, file deletion, or file modification. When the service detects an event of interest, it is forwarded to the registered process. The registered process has a thread (or a pool of threads) dedicated to watching for any events it has registered for. When an event comes in, it is handled as needed.



import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;


public class DirListener {


public static void main(final String[] args) {
try {
Runnable r = new Runnable() {
@Override
public void run() {
while (true) {
handleDirectoryChangeEvent(args[0]);
}
}
};


Thread t = new Thread(r);
t.start();
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}


private static void handleDirectoryChangeEvent(String path) {
try {
Path dir = Paths.get(path);
WatchService watchService = FileSystems.getDefault().newWatchService();
dir.register(watchService, ENTRY_CREATE, ENTRY_MODIFY);
WatchKey watchKey = watchService.take();
for (WatchEvent<?> event : watchKey.pollEvents()) {
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path name = ev.context();
Path child = dir.resolve(name);
System.out.format("%s: %s\n", event.kind().name(), child);
}
        } catch (Exception x) {
            return;
        }
}
}



program output...



ENTRY_CREATE: /home/ssunel/jars/reloadtes1.jar
ENTRY_CREATE: /home/ssunel/jars/reloadtest.jar
ENTRY_CREATE: /home/ssunel/jars/zi3iCChW
ENTRY_CREATE: /home/ssunel/jars/Untitled Document
ENTRY_CREATE: /home/ssunel/jars/ss.txt
ENTRY_CREATE: /home/ssunel/jars/.goutputstream-RVZAHW
ENTRY_MODIFY: /home/ssunel/jars/.goutputstream-RVZAHW
ENTRY_MODIFY: /home/ssunel/jars/.goutputstream-RVZAHW
ENTRY_CREATE: /home/ssunel/jars/ss.txt~
ENTRY_MODIFY: /home/ssunel/jars/reload.jar



Monday, February 27, 2012

Finding the top cpu consumer threads with jconsole

1) Download this jar file


2) Open the jconsole using the plugin


ssunel@javabender:$ /usr/java/bin/jconsole -pluginpath /home/ssunel/Downloads/topthreads.jar

Finding top consumer Java Threads with Unix TOP command and JStack

1)ssunel@VTEKPSSUNEL:~$ top -c -b -H -n1 -d1 | head -n 20 | grep 'java\|CPU'

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND                                                                                    
28763 ssunel    20   0 2893m 821m  10m R  100 10.3   0:38.97 /usr/java/bin/java
28518 ssunel    20   0 2893m 821m  10m S    2 10.3   0:00.30 /usr/java/bin/java
28667 ssunel    20   0 2893m 821m  10m S    2 10.3   0:00.07 /usr/java/bin/java

28733 ssunel    20   0 2893m 821m  10m S    2 10.3   0:00.11 /usr/java/bin/java 

2)Go to : here or use any other converter & convert decimal thread-id(s) [28763  -  28518  -  28667  -  28733 ] to hexedecimal.

Java thread identifiers will be something like that : 
pid    :  nid
28763  : 0x705b
28518 : 0x6f66
28667 : 0x6ffb
28733 : 0x703d

3)ssunel@VTEKPSSUNEL:~$ jstack <pid>

4) Search for the nativeId(s) in the thread dump : nid=0x705b or nid=0x6f66 or nid=0x6ffb or nid=0x703d

Example: 
"SocketListener" daemon prio=10 tid=0x0f474c00 nid=0x705b runnable [0x0386e000]
   java.lang.Thread.State: RUNNABLE
    at java.lang.Throwable.fillInStackTrace(Native Method)
    - locked <0x299364f4> (a java.nio.channels.NotYetBoundException)
    at java.lang.Throwable.<init>(Throwable.java:181)
    at java.lang.Exception.<init>(Exception.java:29)
    at java.lang.RuntimeException.<init>(RuntimeException.java:32)
    at java.lang.IllegalStateException.<init>(IllegalStateException.java:27)
    at java.nio.channels.NotYetBoundException.<init>(NotYetBoundException.java:30)
    at sun.nio.ch.ServerSocketChannelImpl.accept(ServerSocketChannelImpl.java:139)
    - locked <0x6567a198> (a java.lang.Object)
    at com.mycompany.smppgwsocket.smpp34server.Smpp34ServerSocketListener.run(Smpp34ServerSocketListener.java:08)