Saturday, November 21, 2009

Synchronized methods vs Synchronized blocks

These are the two ways of achieving synchronized access in Java. In Java, a method is also a block only, but we normally refer to a block as a part of the method definition. As we know that a thread needs to acquire an appropriate monitor (which it releases when the method returns) before entering any synchronized method/block, so we can easily figure out that in case of a synchronized method a thread may need to have the lock for a longer period of time as compared to that in case of synchronized block.

Another difference is that we don't specify the particular object whose monitor is required to be obtained by a thread for entering a synchronized method whereas we can specify the particular object in case of a synchronized block.

Sunday, November 8, 2009

Can we have two java.lang.Class instances of the same Type?

Can we have two java.lang.Class instances of the same Type?

Yeah... we can have any number of java.lang.Class instances of the same type provided we get the Type loaded by a different ClassLoader instance everytime. Please note that even if we use the same ClassLoader class, but if we use different instances of that class to load a Java Type then each time we'll get a different java.lang.Class instance for the loaded Type. If no ClassLoader instance is explicitly specified then the default ClassLoader instance used which the user doesn't need to create instead JVM creates and maintains for the users.

The loadClass method of the ClassLoader class is used to load any Java Type. This method has two variants:
  • public Class loadClass(String name) - this variant accepts only a String type parameter asking the caller to supply the name of the class
  • protected Class loadClass(String name, boolean resolve) - this variant accepts one additional boolean type parameter asking the caller to specify if the loaded class should be linked immediately or not. Default value of this parameter is false and hence a loadClass(className1) call is internally converted into loadClass(className1, false) call
As you would have noticed that both these methods are instance methods and hence they can be called only on an instance of type ClassLoader. You can create your own instances of any valid ClassLoader type and call the loadClass method to load a Java class to have separate java.lang.Class instances every time you use a separate instance of type ClassLoader to call the loadClass method upon.