Two for one: Class loaders and collection classes
Create custom class loaders and synchronize collection classes
July 5, 2002
Q: Question 1:
I use the Class.forName() method to dynamically load Java classes. However, if I recompile a class and reload it, the new recompiled class does not load. How do I force class reloading?
A:
First, download JUnit. Then look at its junit.runner.TestCaseClassLoader.java
, a class loader able to reload any given class. JUnit uses TestCaseClassLoader
so you do not need to shut down the test GUI (graphical user interface) every time you recompile your test classes. Unfortunately, the latest version cannot reload classes from jar files.
Q: Question 2:
How can I create a synchronized java.util.List?
A: Although the answer to Question 2 lies right in the Javadocs, many developers seem to miss it. The java.util.Vector
, a java.util.List
implementation, is already synchronized. Therefore, you don’t need to do anything special to create a synchronized Vector
. While you asked only about java.util.List
, be aware that java.util.Hashtable
provides a synchronized java.util.Map
.
For all other collection classes—including any java.util.List
implementations—simply use the appropriate method from java.util.Collections
to wrap your collection instance in a synchronized wrapper. As long as you access the collection with the wrapper, the access will be thread-safe. The table below lists what method to use for which collection type.
|
Here’s an example:
List list = Collections.synchronizedList(new LinkedList(...));
The instance referenced by list
is synchronized.
The Collections
class can also perform numerous operations on your collections. For example, you can use Collections
to sort, shuffle, and reverse your collections. You can even use Collections
to wrap your collections so they are unmodifiable.