Java Dynamic Proxy Example

In this post, I will go over the basic constructs of dynamic proxy, followed by some notes and things to watch out when implementing it. First, the 5 elements of a dynamic proxy as implemented in this example:

TestImpl: the class behind the proxy, not to be directly invoked by the client. In some cases, this type may not exist.

TestIF: the proxy interface implemented by TestImpl, and the dynamic proxy. This is the interface type the client should reference. One or more interfaces are required to create dynamic proxy. If there is no such interface, you may need to dynamically generate them with tools like ASM.

TestInvocationHandler: the InvocationHandler that handles method invocation on the proxy from the client. It contains an instance of TestImpl to delegate method invocations to.

Test: the test main class.

$Proxy0: the dynamic proxy that implements TestIF, and the client-facing implementation of TestIF.
public interface TestIF {
String hello(String name);
}
public class TestImpl implements TestIF {
public String hello(String name) {
return String.format("Hello %s, this is %s", name, this);
}
}
import java.lang.reflect.*;
public class TestInvocationHandler implements InvocationHandler {
private Object testImpl;

public TestInvocationHandler(Object impl) {
this.testImpl = impl;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if(Object.class == method.getDeclaringClass()) {
String name = method.getName();
if("equals".equals(name)) {
return proxy == args[0];
} else if("hashCode".equals(name)) {
return System.identityHashCode(proxy);
} else if("toString".equals(name)) {
return proxy.getClass().getName() + "@" +
Integer.toHexString(System.identityHashCode(proxy)) +
", with InvocationHandler " + this;
} else {
throw new IllegalStateException(String.valueOf(method));
}
}
return method.invoke(testImpl, args);
}
}
import java.lang.reflect.*;
public class Test {
public static void main(String... args) {
TestIF t = (TestIF) Proxy.newProxyInstance(TestIF.class.getClassLoader(),
new Class<?>[] {TestIF.class},
new TestInvocationHandler(new TestImpl()));
System.out.printf("t.hello(Duke): %s%n", t.hello("Duke"));
System.out.printf("t.toString(): %s%n", t);
System.out.printf("t.hashCode(): %H%n", t);
System.out.printf("t.equals(t): %B%n", t.equals(t));
System.out.printf("t.equals(new Object()): %B%n", t.equals(new Object()));
System.out.printf("t.equals(null): %B%n", t.equals(null));
}
}
Implementation notes:

When dispatching method invocations on proxy to delegate object, 3 methods from java.lang.Object need special handling: toString(), hashCode() and equals(Object). Since they are related to the proxy object identity, they should be serviced directly by the handler. One option is to base their return values on the proxy param, as in this example.

Other public methods from java.lang.Object are all final, and are not routed to the InvocationHandler by JVM. These methods are:
public final native Class<?> getClass();
public final native void notify();
public final native void notifyAll();
public final native void wait(long timeout) throws InterruptedException;
public final void wait(long timeout, int nanos) throws InterruptedException;
public final void wait() throws InterruptedException
The handler's invoke method should not invoke methods on the proxy object passed in as the first param (except the 6 final methods listed above), to avoid infinite loop and StackOverflowError. For example, this following debug line should not be used:
// AVOID THIS
System.out.printf("proxy=%s, method=%s, args=%s%n",
proxy, method, Arrays.toString(args));
If the handler already knows how to acquire the delegate TestImpl instance, through either direct instantiation or lookup, it can hide it completely from the client. So the only type of TestIF the client knows is the proxy.

The Object[] args passed into handler's invoke method is null, when the invoked method takes no param. This can come as a surprise to many. So a null check is needed before operating on args.

To run this example after compiling all java classes:
$ java Test

t.hello(Duke): Hello Duke, this is TestImpl@a3901c6
t.toString(): $Proxy0@24a37368, with InvocationHandler TestInvocationHandler@66edc3a2
t.hashCode(): 24A37368
t.equals(t): TRUE
t.equals(new Object()): FALSE
t.equals(null): FALSE
To save/keep/dump the generated proxy class file (with non-standard option):
$ java -Dsun.misc.ProxyGenerator.saveGeneratedFiles=true Test
To view the structure of the proxy class:
$ $JAVA_HOME/bin/javap -v \$Proxy0

My Unix Linux Notes

How to extract/expand/explode file.tar.gz, or file.tgz:
gtar xzvf file.tar.gz # if gtar is available, otherwise,
gunzip < file.tgz | tar xvf -

Note the use of < (gunzip file.tgz | tar xvf - won't work). You can always run gunzip and tar in 2 steps, which creates an extra tar file:
gunzip file.tar.gz
tar xvf file.tar
How to find a port number (8080) in use:
netstat -an | grep 8080
How to kill all java processes:
killall java

How to list all background jobs:
jobs
[1] Running ./standalone.sh


How to kill the current background job:
kill %

How to list all java processes:
$JAVA_HOME/bin/jps
$JAVA_HOME/bin/jps -l
$JAVA_HOME/bin/jps -lv
ps -ef | grep java    # more reliable than jps


How to find a java (jboss) process with jps and kill it:
jps | grep jboss | awk '{print $1}' | xargs kill -9


How to find a jboss process with "ps -ef" and kill it:
ps -ef | grep -v grep | grep jboss | awk '{print $2}' | xargs kill -9


Note that in "ps -ef" output, the PID is the 2nd column, after UID. This is different from "ps" and "jps..." output, where PID is column 1.

How to find a file is opened by which program and user (takes a while to finish):
lsof | vim -


How to list all files in current directory in absolute path (for copying the path):
find $PWD


How to sort a list of items (e.g., file paths) and remove duplicates:
sort a.txt > b.txt
uniq b.txt > c.txt

Art Wall Decor | How To Manasge Art Decor for Your Walls

Manage Art Wall Decor
Mirror Wall Decor


When you step inside a house or any place you visit, the first thing you will probably notice is its wall decor. A suitable wall art decor can definitely catch attention and can even impress the guests and anyone who will be able to see it. If you are a home owner, you might be thinking how can you make your home a much better place for your family to enjoy.

A wall art and decor must be best in terms of uniqueness, style, and cost. Then go for the type which you have planned. Decorating ideas is very crucial in terms of selecting a wall art and decor. When selecting wall art, we have several options, including paintings, grilles, mirrors, shelves, and others. The choices we make regarding these items are important. Some of the most important selections involve the type of wall art is size, the arrangement we will use, and the wall art's color.
Grouping Photographs and other wall decors:
Framed photos, art prints and posters can be hung by grouping them to look professional. It shows unity when you display art prints, photographs and pictures together. Even pictures with different shapes and sizes but having the same frame color and mount will show unity.

It is also very important to hang frames with uniform spacing. The common mistake in hanging frames is to hang them higher than "eye level" of an average person on walls of the hallways or entry ways where people view them while standing. When hanging them in the walls of the living room and dining area, framed displays should be at eye level which is about 6 to 9 inches above the furniture when you're seated. To manage wall art decor you must read 5 tips from Amy C below:

Dealing with large walls:
The wide space you have to cover makes it a little harder to decorate large walls than smaller ones. When things you hang on the wall are not in proportion, it looks awkward. An effective way to deal with large walls is to hang framed photographs across the wall in several rows arranged in straight line or in any pattern you want.

Using Mirrors and Metal Art:
A mirror can make a room look larger and it can add dimensions. Wall mirrors come in different styles and designs. It is also a good way to decorate your wall with metal arts crafted from brass or silver. These kinds of wall art are unique and not so many people use them.

Tiles are contemporary wall decors:
You can easily buy some pieces of tiles and add your personal artistic touch.

Manage Art Wall Decor
Curtain Wall Decor
Curtains and shelves:
Curtains are always important to add a warm and cozy look. Curtains enhance the look of the wall. Shelves add beauty when placed across a wall where you can display books and other decors.


Manage Art Wall Decor
Wall Shelves Decor
You can create your own unique style. Art decors can easily enhance the indoor mood. This is an excellent opportunity to show your personal expression through the decors that you hang on your wall. It can be classic, modern, funny, romantic or contemporary. You'll never be short of choices to make a great looking wall.

Extend Thread vs implement Runnable

There are two ways to create your own thread type: subclass java.lang.Thread class, or implementing java.lang.Runnable and pass it to Thread constructor or java.util.concurrent.ThreadFactory. What is the difference, and which one is better?

1, The practical reason is, a Java class can have only one superclass. So if your thread class extends java.lang.Thread, it cannot inherit from any other classes. This limits how you can reuse your application logic.

2, From a design point of view, there should be a clean separation between how a task is identified and defined, between how it is executed. The former is the responsibility of a Runnalbe impl, and the latter is job of the Thread class.

3, A Runnable instance can be passed to other libraries that accept task submission, e.g., java.util.concurrent.Executors. A Thread subclass inherits all the overhead of thread management and is hard to reuse.

4, Their instances also have different lifecycle. Once a thread is started and completed its work, it's subject to garbage collection. An instance of Runnalbe task can be resubmitted or retried multiple times, though usually new tasks are instantiated for each submission to ease state management.

Followers

Pageviews Last 7 Days