Posted on Apr 26, 2008

A live template for Java 5 Locks

Every time I used Java 5 new locks I found myself writing the same lock.lock(); try {…} finally {lock.unlock();} over and over again. Sometimes I’ve even coded, unintentionally, a lock.lock() instead of a lock.unlock(). Because of this and other reasons which I won’t share (i.e., I don’t like to copy & paste stuff) :) I decided to automate the addition of the Java 5 locks via IntelliJ live templates. How is this going work? Simply type lock[tab] and voila you will have a new a Java 5 synchronized block written for you


$LOCK$.lock();
try {
    //tocode
} finally {
    $LOCK$.unlock();
}

p.s.,
I almost forgot. In order to make the previous live template to work for both write and read locks, you will have to set the $LOCK$ variable as a variable of the type Lock (i.e., variableOfType(“Lock”)).

Posted on Apr 25, 2008

Binding data to Java enums…

Paul Stovell blogged about binding data to enums in C#. Here is how I would implement this technique in Java….

First, an annotation that I will use to bind data to my enum


@Target(Element.FIELD)
@Retention(RententionPolicy.RUNTIME)
public @interface Config {
	String name();
	String alias();
}

Then, here is my enum


public enum Role {
@Config(name="James Bond", alias = "Agent 007")
AGENT;

// static attribute that will allow us to
// config the enum only once.
private static boolean isConfigured = false;
static {
if(!isConfigured){
    configureRole();
}
}

private RoleValue value;
Role(){
}

public RoleValue getValue(){
    if(value == null){
        throw new IllegalStateException();
    }
    return new RoleValue(value);
}

private static void configureRole(){
    final Field[] declaredEnums = Role.class.getDeclaredFields();
    for(Field eachField : declaredEnums){
        final Config placedConfig = eachField.getAnnotation(Config.class);

        final boolean isValuesField     = eachField.getName().equals("$VALUES");
        final boolean isRefreshedField  = eachField.getName().equals("isConfigured");
        final boolean isValueField      = eachField.getName().equals("value");

        // ... we want to igonore the VALUES, isConfigured, and value fields.
        // ... we care only about the Role's enum instances.
        if(isValuesField || isRefreshedField || isValueField){
            continue;
        }

        final String name           = placedConfig.name();
        final String alias          = placedConfig.alias();
        final Enum<Role> actualEnum = valueOf(eachField.getName());

        final RoleValue enumValue   = new RoleValue(name, alias);

        try {
            final Field field = actualEnum.getDeclaringClass().getDeclaredField(
                  "value"
             );
            field.setAccessible(true);
            field.set(actualEnum, enumValue);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

        isConfigured = true;

    }
}

/**
 * a updatable value
 */
public static class RoleValue {
    private final String name;
    private final String alias;
    public RoleValue(String name, String alias){
        this.name   = name;
        this.alias  = alias;
    }

    public RoleValue(RoleValue value){
        this(value.getName(), value.getAlias());
    }

    public String getName(){
        return name;
    }

    public String getAlias(){
        return alias;
    }
}
}

interesting way to play with Java 5.0′s enums…. cool :)

Posted on Apr 19, 2008

Debugging windows services in .NET

The other day I was trying to test a Windows Service that I implemented for a friend. I thought to myself that this was going to be an easy endeavor. I just needed to install the service, run it, set some breakpoints, then attach its process to the debugger and that was it. Oh boy… I was SOOO wrong. It was not as easy as I thought it would be.

I cannot remember how much time I spent trying to make it work using the above approach. It was until I decided not to rely on this “supposedly clean” way for debugging .NET Windows Service applications that I was able to complete my testing, so I could tell my friend “here is the service.”

Here is what I wrote to solve my debugging problem:


static void Main()
{
#if (!DEBUG)
    System.ServiceProcess.ServiceBase[] ServicesToRun;
    ServicesToRun = new System.ServiceProcess.ServiceBase[]{
         new MyService()
    };
    System.ServiceProcess.ServiceBase.Run(ServicesToRun);
#else
    // Debug code: this allows the process to run
    // as a non-service.
    // Put a breakpoint on the following line
    MyService service = new MyService();
    System.Threading.Thread.Sleep(
      System.Threading.Timeout.Infinite
    );
#endif
}

I know, I know, this is not pretty, but It works. At the end that’s the only thing that matters :-)