About Me

My photo
Bangalore, Karnataka, India

Saturday, December 11, 2010

synchronization is not just mutual exclusion

When I was taking a interview of Java developers and talking to my colleagues, In almost all the cases I was asking a simple trivial question "What is synchronization?". Surprisingly I haven't seen this question answered 100%. The gist of all the answers is synchronization is required for stop two threads running concurrently some code (mutual exclusion).
Is synchronization just a mutual exclusion. Certainly not. There is more to Synchronization than just mutual exclusion. Synchronization ensures that memory writes by a thread before or during a synchronized block are made visible in a predictable manner to other threads which synchronize on the same monitor. After we exit a synchronized block, we release the monitor, which has the effect of flushing the cache to main memory, so that writes made by this thread can be visible to other threads. Before we can enter a synchronized block, we acquire the monitor, which has the effect of invalidating the local processor cache so that variables will be reloaded from main memory. We will then be able to see all of the writes made visible by the previous release. There is some ugly truth that compiler or cache can reorder the non synchronized code with few exceptions of volatile. Keep watching I will write another blog on it as well.

Source of information:  http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html

Wednesday, June 16, 2010

DCL and Synchronization

Myself being a C++ developer before, was writing code with Double checked lock pattern untill I realized that doing so is a crime in Java. The reason goes like this, the JVM implementor and the compiler are free to reorder the code in the non-synchronized block and we may endup getting the stale object reference in many a cases. But in few implementations is works fine as read over google. So the thumb rule is no DCL in JAVA. There were few links which tells there is some JSR coming in the way to solve this (JMM specs for this).

Volatile is the solution for this.

Thursday, May 13, 2010

Peristing java.util.Properties :hibernate

Hibernate gives you option to store only map by default. If you need to store java.util.Properties object to database writing a UserType around PersistenceMap will not help unless your domain object has a setter method which accepts Map as argument. The solution I took is to write a tupilizer like below.

-----------------------------------------------------
import java.lang.reflect.Method;
import java.util.Properties;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.mapping.Map;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.hibernate.property.Setter;
import org.hibernate.tuple.entity.EntityMetamodel;
import org.hibernate.tuple.entity.PojoEntityTuplizer;
/**
* Class to convert the PersistentMap to Properties in setter.
* Implementation is backed by PojoEntityTuplizer and only if
* property type is Properties value to set is Map this will convert
* and return the value.
*
* @author krishna.arani
*/
public class PropertyTuplizer extends PojoEntityTuplizer {
public PropertyTuplizer(EntityMetamodel entityMetamodel,
PersistentClass mappedEntity) {
super(entityMetamodel, mappedEntity);
}
@Override
protected Setter buildPropertySetter(Property mappedProperty,
PersistentClass mappedEntity) {
final Setter setter = super.buildPropertySetter(mappedProperty,
mappedEntity);
if (!(mappedProperty.getValue() instanceof Map)) {
return setter;
}
return new Setter() {
private static final long serialVersionUID = 1L;
@Override
public Method getMethod() {
return setter.getMethod();
}
@Override
public String getMethodName() {
return setter.getMethodName();
}
@Override
public void set(Object target, Object value,
SessionFactoryImplementor sessionFactoryImplementor)
throws HibernateException {
Object convertedValue = value;
if (value instanceof java.util.Map) {
Class parameterType[] = getMethod().getParameterTypes();
// if required to convert from map
if (Properties.class.isAssignableFrom(parameterType[0])
&& !(value instanceof Properties)) {
Properties props = new Properties();
java.util.Map castedValue = (java.util.Map) value;
Set entries = ((java.util.Map) value)
.entrySet();
for (java.util.Map.Entry entry : entries) {
props.put(entry.getKey(), entry.getValue());
}
convertedValue = props;
}
}
setter.set(target, convertedValue, sessionFactoryImplementor);
}
};
}
}

------------------------------------
The idea is to override the setter method so that it converts map to Properties before invoking the set on the domain object.

Here is the sample of class and hbm Site with connection parameters as java.util.Properties.




Class Site{
String SiteId;
java.util.Properties connectionParameters;

public String getSiteId(){
return siteId;
}

public void setSiteId(String siteId){
this.siteId = siteId;
}

public java.util.Properties getConnectionParameters(){
return connectionPerameters;
}

public void setConnectionParameters(java.util.Properties props){
this. connectionPerameters = props;
}

}

-----------------------
hbm:


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<hibernate-mapping>

<class name="Site" >

<tuplizer class="PropertyTuplizer"
entity-mode="pojo" />

<id name="siteId" type="java.lang.String" column="siteid" />

<map name="connectionParameters">
<key column="siteid" />
<map-key type="java.lang.String" column="propertyName" />
<element type="java.lang.String" column="propertyValue" />
</map>

</class>

</hibernate-mapping>





Friday, April 2, 2010

Java Beans Introspector

Before we proceed further about the Java.beans.Introspector let me present a statement that, I strongly believe. "Use reflection only as a last option". Most of the cases we use reflection just to reduce the number of lines of code or just to avoid few more classes to be added to the context, some times just not knowing that reflective code executes slower than the normal code. I am open to correct and learn if any of you defer from it.

No doubt javas reflection and java.beans.Introspector very powerful and useful, extensively used in many softwares. Introspector class is standard way for tools to learn about the properties, events, and methods supported by a target Java Bean. Many places I have seen code using the low level reflection where Introspector will be a better candidate. see java.beans.Introspector javadoc for more information.

When ever using Introspector, <Class-Name>BeanInfo is searched first before calculating the BeanInfo for itself.

Last but not the least when ever running applications with different classe loaders, infact in general if we are destroying the ClassLoader or context thumb rule is that we call Introspector.flushCaches().

Sunday, March 28, 2010

Most neglected truth about SWITCH CASE

Many of a times, I have come across the code where if/else used instead of the switch case. Its not that annoying for readability but many of us actually forget the truth that switch case statements generate jump tables which are faster while executing compared to if/else. I agree that we get very minimal efficiency compared to other improvements but we get some improvement in many of the cases. If the case statements are more dense then the effect more. Java allows integer types (see java for more info on integer types. even char is integer type) and enums to be used in switch case. From now onwards we should keep in mind that use switch/case where ever possible, and avoid using default case if possible for more efficiency. This will beautify the code also.

This comment applies to other languages like C/C++ also.

Finding the jar/jars from which the class/resource is loaded

There is always a very good chance of having the same class in two different jars available in the class path of the class loader. Its the fact that which ever jar comes first in the search is loaded and used. But if you wonder from which jar or path the class/resource (may be a properties file) is loaded from. Here you go. just write the following snippet of code in the context you want to know the resource location.

URL url = Thread.currentThread().getContextClassLoader().getResource("com/example/ClassToFind.class");

if(url != null){
System.out.println(" location of resource in context "+url.getPath());
} else {
url = super.getClass().getClassLoader().getResource(name);
if(url != null){
System.out.println(" location of resource class loder "+ super.getClass().getClassLoader() + " is "+ url.getPath());
}
}

If the ClassToFind.class is in example.jar then the above will print

location-of-example.jar!com/example/ClassToFind.class

If you want to find all the jars containg the resource then you can use this instead.

java.util.Enumeration urls = Thread.currentThread().getContextClassLoader()
.getResources("");

while(urls.hasMoreElements()){
System.out.println(urls.nextElement().getPath());
}

There are few other ways to get around this. If you have put Java in verbose mode or If you are running in JBOSS you can enable the class loader logs. see JBOSS docs for more information.

Wednesday, March 24, 2010

Allowing only defined classes to access the method in Java

If you wonder how do you allow only a specific class to be allowed to access your method. Here you go. You can check the class name on the stack and do take a decision whether you allow are reject permission to.

Class callerClass = Reflection.getCallerClass(2); //2 stack position
If(!validList_.contains(callerClass)) {
Throw new IllegalAccessException(); or SecurityException();
}

In the above snippet validList is list of classes you wish to allow. This is barrowed from the sun.misc.Unsafe classe.