1.Event publishing - on method x(), transparently call y() or send message z.
2.Transaction management (for db connections or other transactional ops)
3.Thread management - thread out expensive operations transparently.
4.Performance tracking - timing operations checked by a CountdownLatch, for example.
5.Connection management - thinking of APIs like Salesforce's Enterprise API that require clients of their service to start a session before executing any operations.
6.Changing method parameters - in case you want to pass default values for nulls, if that's your sort of thing.
Those are just a few options in addition to validation and logging like you've described above. FWIW, JSR 303, a bean validation specification, has an AOP-style implementation in Hibernate Validator, so you don't need to implement it for your data objects specifically. Spring framework also has validation built in and has really nice integration with AspectJ for some of the stuff described here.
7. Another useful side of a dynamic proxy is when you want to apply the same operation to all methods. With a static proxy you'd need a lot of duplicated code (on each proxied method you would need the same call to a method, and then delegate to the proxied object), and a dynamic proxy would minimize this.
Monday, March 28, 2011
How Java AOP implemented
How Java AOP works
Class-weaving-based, such as AspectJ and JBoss AOP. Core and crosscutting concerns are implemented independently. Class weaving is the process of integrating the concern implementations to form the final system. Weaving can be performed at compile, load, and run time. Both AspectJ and JBoss AOP are very powerful AOP implementations. They provide field interception, caller side interception, and constructor interception.
Proxy-based, such as Spring AOP, Nanning, and dynaop. With proxies, method invocations on an object can be intercepted to inject custom code. The aforementioned AOP frameworks use JDK dynamic proxy, CGLIB proxy, or both. Unlike the class-weaving-based ones, proxy-based AOP frameworks are simpler and often focus on method interception. Most of the time, Java developers use method interception only. Some proxy-based AOP implementations, such as Spring AOP, provide close integration with AspectJ to take advantage of its capabilities.
What if you want to proxy legacy classes that do not have interfaces? You can use CGLIB. CGLIB is a powerful, high-performance code generation library. Under the cover, it uses ASM, a small but fast bytecode manipulation framework, to transform existing byte code to generate new classes. CGLIB is faster than the JDK dynamic proxy approach. Essentially, it dynamically generates a subclass to override the non-final methods of the proxied class and wires up hooks that call back to the user-defined interceptors.
1. Dynamic proxy using InvocationHandler
public Object invoke(Object target, Method method, Object[] arguments) {
System.out.println("before method " + method.getName());
return method.invoke(obj, args);
}
}
2. Java byte-code transformation:
http://asm.ow2.org/doc/tutorial-annotations.html
Refere this article : http://today.java.net/pub/a/today/2005/11/01/implement-proxy-based-aop.html
Class-weaving-based, such as AspectJ and JBoss AOP. Core and crosscutting concerns are implemented independently. Class weaving is the process of integrating the concern implementations to form the final system. Weaving can be performed at compile, load, and run time. Both AspectJ and JBoss AOP are very powerful AOP implementations. They provide field interception, caller side interception, and constructor interception.
Proxy-based, such as Spring AOP, Nanning, and dynaop. With proxies, method invocations on an object can be intercepted to inject custom code. The aforementioned AOP frameworks use JDK dynamic proxy, CGLIB proxy, or both. Unlike the class-weaving-based ones, proxy-based AOP frameworks are simpler and often focus on method interception. Most of the time, Java developers use method interception only. Some proxy-based AOP implementations, such as Spring AOP, provide close integration with AspectJ to take advantage of its capabilities.
What if you want to proxy legacy classes that do not have interfaces? You can use CGLIB. CGLIB is a powerful, high-performance code generation library. Under the cover, it uses ASM, a small but fast bytecode manipulation framework, to transform existing byte code to generate new classes. CGLIB is faster than the JDK dynamic proxy approach. Essentially, it dynamically generates a subclass to override the non-final methods of the proxied class and wires up hooks that call back to the user-defined interceptors.
1. Dynamic proxy using InvocationHandler
public Object invoke(Object target, Method method, Object[] arguments) {
System.out.println("before method " + method.getName());
return method.invoke(obj, args);
}
}
2. Java byte-code transformation:
http://asm.ow2.org/doc/tutorial-annotations.html
Refere this article : http://today.java.net/pub/a/today/2005/11/01/implement-proxy-based-aop.html
Java classpath discovery
Library which allows discovering classes at runtime. In Java one can use
ClassLoader.getResourceAsInputStream(resource);
to load the data from the CLASS_PATH provided that you know the name of the resource. This library allows you to discover what Java packages and classes are available at runtime.
ClassPathFactory factory = new ClassPathFactory();
ClassPath classPath = factory.createFromJVM();
for (String packageName : classPath.listPackages("")) {
System.out.println(packageName);
}
ClassLoader.getResourceAsInputStream(resource);
to load the data from the CLASS_PATH provided that you know the name of the resource. This library allows you to discover what Java packages and classes are available at runtime.
ClassPathFactory factory = new ClassPathFactory();
ClassPath classPath = factory.createFromJVM();
for (String packageName : classPath.listPackages("")) {
System.out.println(packageName);
}
Catching Exception in Threads
Java 5 introduced a new way to catch unexpected exceptions: Thread.UncaughtExceptionHandler. This is an interface with the following API:
public interface UncaughtExceptionHandler {
void uncaughtException(Thread t, Throwable e);
}
Your job is to write a class that implements this interface. You then register your implementation on a per-thread basis, or globally for every thread. To register your handler for a single thread you do something like this:
Thread.currentThread().setUncaughtExceptionHandler(new MyExceptionHandler());
To register your handler for every thread, do this:
Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler());
Notice that setDefaultUncaughtExceptionHandler(...) is a static method in the Thread class, while setUncaughtExceptionHandler(...) is a non-static method.
Simple enough. Let’s add an uncaught exception handler.
MyExceptionHandler
Here is a simple uncaught exception handler that shows the exception message in a dialog box.
public class MyExceptionHandler implements Thread.UncaughtExceptionHandler {
public void uncaughtException(final Thread t, final Throwable e) {
if (SwingUtilities.isEventDispatchThread()) {
showException(t, e);
} else {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
showException(t, e);
}
});
}
}
private void showException(Thread t, Throwable e) {
String msg = String.format("Unexpected problem on thread %s: %s",
t.getName(), e.getMessage());
logException(t, e);
// note: in a real app, you should locate the currently focused frame
// or dialog and use it as the parent. In this example, I'm just passing
// a null owner, which means this dialog may get buried behind
// some other screen.
JOptionPane.showMessageDialog(null, msg);
}
private void logException(Thread t, Throwable e) {
// todo: start a thread that sends an email, or write to a log file, or
// send a JMS message...whatever
}
}
To use this handler, you must register it. Simply modify the code as follows:
public static void main(String[] args) {
Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler());
...
Now, whenever an “unexpected” exception occurs, MyExceptionHandler kicks in and shows this lovely dialog box:
public interface UncaughtExceptionHandler {
void uncaughtException(Thread t, Throwable e);
}
Your job is to write a class that implements this interface. You then register your implementation on a per-thread basis, or globally for every thread. To register your handler for a single thread you do something like this:
Thread.currentThread().setUncaughtExceptionHandler(new MyExceptionHandler());
To register your handler for every thread, do this:
Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler());
Notice that setDefaultUncaughtExceptionHandler(...) is a static method in the Thread class, while setUncaughtExceptionHandler(...) is a non-static method.
Simple enough. Let’s add an uncaught exception handler.
MyExceptionHandler
Here is a simple uncaught exception handler that shows the exception message in a dialog box.
public class MyExceptionHandler implements Thread.UncaughtExceptionHandler {
public void uncaughtException(final Thread t, final Throwable e) {
if (SwingUtilities.isEventDispatchThread()) {
showException(t, e);
} else {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
showException(t, e);
}
});
}
}
private void showException(Thread t, Throwable e) {
String msg = String.format("Unexpected problem on thread %s: %s",
t.getName(), e.getMessage());
logException(t, e);
// note: in a real app, you should locate the currently focused frame
// or dialog and use it as the parent. In this example, I'm just passing
// a null owner, which means this dialog may get buried behind
// some other screen.
JOptionPane.showMessageDialog(null, msg);
}
private void logException(Thread t, Throwable e) {
// todo: start a thread that sends an email, or write to a log file, or
// send a JMS message...whatever
}
}
To use this handler, you must register it. Simply modify the code as follows:
public static void main(String[] args) {
Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler());
...
Now, whenever an “unexpected” exception occurs, MyExceptionHandler kicks in and shows this lovely dialog box:
Friday, September 24, 2010
load() vs get() hibernate
Hibernate load vs. Hibernate get Methods
Well, if you were to compare the load and get methods of the Hibernate Session, you'd think that they looked pretty darned similar; and you'd be correct, but there are subtle and very important differences.
First of all, the get method hits the database as soon as it is called. So, using the Hibernate Session's get method will always trigger a database hit. On the other hand, the load method only hits the database when a particular field of the entity is accessed. So, if we use the load method to retrieve an entity, but we never actually access any of the fields of that entity, we never actually hit the database. Pretty kewl, eh?
Well, actually, as kewl as the load method might sound, it actually triggers more problems than it solves, and here's why. If you initialize a JavaBean instance with a load method call, you can only access the properties of that JavaBean, for the first time, within the transactional context in which it was initialized. If you try to access the various properties of the JavaBean after the transaction that loaded it has been committed, you'll get an exception, a LazyInitializationException, as Hibernate no longer has a valid transactional context to use to hit the database.
So, while this code will work just fine?..
session.beginTransaction();
User user=(User)session.load(User.class, new Long(1));
System.out.println(user.getPassword());
session.getTransaction().commit();
.. this code will fail ?..
session.beginTransaction();
User user=(User)session.load(User.class, new Long(1));
session.getTransaction().commit();
System.out.println(user.getPassword());
.. and generate the following error, telling you that since the transaction was committed, there was no valid Session in which a read transaction against the database could be issued:
org.hibernate.LazyInitializationException:
could not initialize proxy - no Session
When to use get? When to use load?
So, after comparing and contrasting the load and get methods, the natural question that arises is "when do I use the get, and when do I use load?" It's a good question.
For the most part, you'll probably use the get method most often in your code. If you ever want to use the JavaBean that you are retrieving from the database after the database transaction has been committed, you'll want to use the get method, and quite frankly, that tends to be most of the time.
-- From Hibernate made easy
Well, if you were to compare the load and get methods of the Hibernate Session, you'd think that they looked pretty darned similar; and you'd be correct, but there are subtle and very important differences.
First of all, the get method hits the database as soon as it is called. So, using the Hibernate Session's get method will always trigger a database hit. On the other hand, the load method only hits the database when a particular field of the entity is accessed. So, if we use the load method to retrieve an entity, but we never actually access any of the fields of that entity, we never actually hit the database. Pretty kewl, eh?
Well, actually, as kewl as the load method might sound, it actually triggers more problems than it solves, and here's why. If you initialize a JavaBean instance with a load method call, you can only access the properties of that JavaBean, for the first time, within the transactional context in which it was initialized. If you try to access the various properties of the JavaBean after the transaction that loaded it has been committed, you'll get an exception, a LazyInitializationException, as Hibernate no longer has a valid transactional context to use to hit the database.
So, while this code will work just fine?..
session.beginTransaction();
User user=(User)session.load(User.class, new Long(1));
System.out.println(user.getPassword());
session.getTransaction().commit();
.. this code will fail ?..
session.beginTransaction();
User user=(User)session.load(User.class, new Long(1));
session.getTransaction().commit();
System.out.println(user.getPassword());
.. and generate the following error, telling you that since the transaction was committed, there was no valid Session in which a read transaction against the database could be issued:
org.hibernate.LazyInitializationException:
could not initialize proxy - no Session
When to use get? When to use load?
So, after comparing and contrasting the load and get methods, the natural question that arises is "when do I use the get, and when do I use load?" It's a good question.
For the most part, you'll probably use the get method most often in your code. If you ever want to use the JavaBean that you are retrieving from the database after the database transaction has been committed, you'll want to use the get method, and quite frankly, that tends to be most of the time.
-- From Hibernate made easy
Wednesday, September 22, 2010
IN vs EXISTS
bY Tome Kyte :
can you give me some example at which situation
IN is better than exist, and vice versa.
and we said...
Well, the two are processed very very differently.
Select * from T1 where x in ( select y from T2 )
is typically processed as:
select *
from t1, ( select distinct y from t2 ) t2
where t1.x = t2.y;
The subquery is evaluated, distinct'ed, indexed (or hashed or sorted) and then joined to
the original table -- typically.
As opposed to
select * from t1 where exists ( select null from t2 where y = x )
That is processed more like:
for x in ( select * from t1 )
loop
if ( exists ( select null from t2 where y = x.x )
then
OUTPUT THE RECORD
end if
end loop
It always results in a full scan of T1 whereas the first query can make use of an index
on T1(x).
So, when is where exists appropriate and in appropriate?
Lets say the result of the subquery
( select y from T2 )
is "huge" and takes a long time. But the table T1 is relatively small and executing (
select null from t2 where y = x.x ) is very very fast (nice index on t2(y)). Then the
exists will be faster as the time to full scan T1 and do the index probe into T2 could be
less then the time to simply full scan T2 to build the subquery we need to distinct on.
Lets say the result of the subquery is small -- then IN is typicaly more appropriate.
If both the subquery and the outer table are huge -- either might work as well as the
other -- depends on the indexes and other factors.
can you give me some example at which situation
IN is better than exist, and vice versa.
and we said...
Well, the two are processed very very differently.
Select * from T1 where x in ( select y from T2 )
is typically processed as:
select *
from t1, ( select distinct y from t2 ) t2
where t1.x = t2.y;
The subquery is evaluated, distinct'ed, indexed (or hashed or sorted) and then joined to
the original table -- typically.
As opposed to
select * from t1 where exists ( select null from t2 where y = x )
That is processed more like:
for x in ( select * from t1 )
loop
if ( exists ( select null from t2 where y = x.x )
then
OUTPUT THE RECORD
end if
end loop
It always results in a full scan of T1 whereas the first query can make use of an index
on T1(x).
So, when is where exists appropriate and in appropriate?
Lets say the result of the subquery
( select y from T2 )
is "huge" and takes a long time. But the table T1 is relatively small and executing (
select null from t2 where y = x.x ) is very very fast (nice index on t2(y)). Then the
exists will be faster as the time to full scan T1 and do the index probe into T2 could be
less then the time to simply full scan T2 to build the subquery we need to distinct on.
Lets say the result of the subquery is small -- then IN is typicaly more appropriate.
If both the subquery and the outer table are huge -- either might work as well as the
other -- depends on the indexes and other factors.
Tuesday, September 21, 2010
Producer Consumer using concurrent : by Enno Shioji
public class Main {
public static void main(String[] args){
//The numbers are just silly tune parameters. Refer to the API.
//The important thing is, we are passing a bounded queue.
ExecutorService consumer = new ThreadPoolExecutor(1,4,30,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(100));
//No need to bound the queue for this executor.
//Use utility method instead of the complicated Constructor.
ExecutorService producer = Executors.newSingleThreadExecutor();
Runnable produce = new Produce(consumer);
producer.submit(produce);
}
}
class Produce implements Runnable{
private final ExecutorService consumer;
public Produce(ExecutorService consumer) {
this.consumer = consumer;
}
@Override
public void run() { while(!Thread.isInterrupted){
//do stuff
Pancake cake = Pan.cook();
Runnable consume = new Consume(cake);
consumer.submit(consume);
}}
}
class Consume implements Runnable{
private final Pancake cake;
public Consume(Pancake cake){
this.cake = cake;
}
@Override
public void run() {
cake.eat();
}
}
Subscribe to:
Posts (Atom)
