Wednesday 19 September 2012

New Java 7 Classloader locking

Java 7 has improved the use of class loaders by modifying the locking mechanism to avoid
deadlocks. In multi-threaded custom class loaders prior to Java 7, certain custom class
loaders were prone to deadlocks, when they used a cyclic delegation model.

Consider the following scenario. Thread1 tries to use a ClassLoader1 (locking ClassLoader1)
to load class1. It then delegates the loading of class2 to ClassLoader2. At the same time,
Thread2 uses ClassLoader2 (locking ClassLoader2) to load class3, and then delegates the
loading of class4 to ClassLoader1. Since both class loaders are locked and both the threads
need both loaders, a deadlock situation occurs.

The desired behavior of a concurrent class loader is to load different classes from the same
instance of the class loader concurrently. This requires locking at a finer level of granularity,
such as locking a class loader by the name of the class being loaded.

Synchronization should not be done at the class loader level. Instead, a lock should be made
on a class level, where the class loader allows only a single instance of the class to be loaded
at a time by that class loader.

Some class loaders are capable of loading classes concurrently. This type of class loader is
called parallel capable class loaders. They are required to register themselves during their
initialization process using the registerAsParallelCapable method.

No comments:

Post a Comment