Java WTF: Reflection API and Annotations

I got some exposure to custom Java 5 Annotations today and came across a noobie mistake. Here's my annotation:
public @interface Annotated {
}
Pretty simple, right? Here's a test class that uses the annotation:
import java.lang.annotation.Annotation;

@Annotated
public class Main {
    public static void main(String[] args) throws Exception {
        for(Annotation ann: Main.class.getAnnotations()) {
            System.out.println(ann);
        }
    }
}
What does this print? ... Nothing! Well, WTF? Turns out Annotations are not run-time accessible unless you declaratively specific it via @Retention. The updated annotation looks like this:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface Annotated {

}
By default, the Retention is specified with RetentionPolicy.CLASS which, per the javadocs, "Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time." RetentionPolicy.RUNTIME allows the annotation "to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively." File this one under, RTFM.

Java WTF: Calendar vs Date

I've been doing some date math at work and I came across something I thought was wack. Check this out:
Calendar cal1 = Calendar.getInstance();
Thread.sleep(500);
Calendar cal2 = Calendar.getInstance();
Thread.sleep(500);
Date now = new Date();

System.out.println(cal1.before(cal2));
System.out.println(cal1.before(now));
What do you think this snippet prints (It compiles, I promise!)? Looking at the code, it shows that we are getting three snapshots in time, waiting half a second between snapshots, and assigning those values to cal1,cal2, and now, respectively. I put in the Thread.sleep() to illustrate the point more clearly. The first print statement compares the first and second snapshots in time, returning true if the first is before the second. The second print statement returns true if the first is before the third snapshot. Logically, we would expect both print statements to prints true. However, this outputs:
true
false
But, how could the first snapshot be before the second snapshot but not the third? Putting up the javadocs, gives us our answer. The Calendar before and after methods always returns false if you don't pass it a Calendar object. Why? I have no idea. Why not just have the method signature take a Calendar object? I mean, I guess this allows you to extend Calendar to be able to call after/before on whatever kind of classes you want to support...but does it really make sense to compare a Calendar to a Monkey class? This is what I call a Java WTF.

Hacks, Tricks, and Techniques

I'm reading Out Of Their Minds - The Lives and Discoveries of 15 Great Computer Scientists by Dennis Shasha and Cathy Lazere.  I'm almost half way through but I just read an awesome quote that I wanted to share:
In the culture of computer science, an idea that works in one situation is called a hack, an idea that works twice is called a trick, and an idea that works often and pervasively is called a technique.

- Out Of Their Minds, 1998

Eclipse + Leopard = Crash?

I recently upgraded to Leopard on my work MacBook Pro. In Eclipse, one of the first things I ran into was anytime I tried to do Open Resource (Shift + ⌘ + R) to open a file resource, Eclipse would crash with a nasty exception. Exception Type: EXC_BAD_ACCESS (SIGBUS) After doing a bit of googling, this seems to be a bug in SWT for Leopard (see here). I upgraded my Eclipse to the 3.4 Stream Stable Build found at http://download.eclipse.org/eclipse/downloads/ and my problems have seem to gone away. It's got a pretty cool new splash screen too :)

Javascript Password Revealer using Prototype

Inspired by the latest Coding Horror post, here's an code snippet that allows you to implement a password revealer using the Prototype JavaScript library.
function togglePassword(elem){

        var e=$(elem);

        e.type=='password' ? e.type='input' : e.type='password';

}
Check it out in action below.
<br /> Check it out in action <a href="http://static.notedpath.com/password_revealer.html">here</a>.<br />
I wouldn't mind seeing more web forms adding this feature for password fields.

Using JMeter for load testing

I came across JMeter a while back but never got a chance to try it out. From the JMeter website:
Apache JMeter is a 100% pure Java desktop application designed to load test functional behavior and measure performance. It was originally designed for testing Web Applications but has since expanded to other test functions.
This weekend I was able to test load on my 256 slice which this blog is running on. Here's what I did:
  1. Download the binary You can get the binary here.
  2. Unzip the tarball/zip file I extracted it file to /Users/theo/tools/jakarta-jmeter-2.3.1
  3. Start up JMeter Go to the bin directory. Run jmeter.sh (jmeter.bat if using Windows) from the command line.
  4. Create a Test Plan Just give a name and any description you want for your test plan.
  5. Create a Thread Group A thread group allows you to specify the amount of load you want to simulate. Select your test plan from the left Tree view, right-click, and select Add -> Thread Group. Configurable fields include:
    • Number of threads - the number of connections or users you want to simulate
    • Ramp up period - the amount of time in seconds to take to reach the number of threads specified. If you choose 0, all of the threads will be created at the start of the test.
    • Loop count - you can specify to loop indefinitely or provide a number of times to run through the test.
  6. Add a Sampler A sampler is a type of request you want to make. In this example, I used an HTTP request to test load to a web server. It's good to note JMeter supports multiple types of samplers including web services, JMS, and JDBC. Add a sampler by selecting the Thread Group you just created, right-click, select Add -> Sampler -> HTTP Request. Configurable properties include:
    • Server Name - what the ip or url is to the server the request it to
    • Port - the port the server is listening to
    • Protocol - the protocol (http, https, etc)
    • Method - HTTP method (POST,GET, PUT, DELETE, etc)
    • Path - the URL path to request
  7. Add a Listener A listener allows you to collect data points and display them in some fashion like a graph or a table. I used the Graph Results listener by selecting the Thread Group, right-click, select Add -> Listener -> Graph Results.
  8. Run the test! Now we are ready to run the test. From the file menu bar, select Run ->Start. You will be prompted to save your test plan. You can save it or just hit "No". You should see data points begin to be plotted on the Graph Result or whatever listener you selected. I monitored the usage from my slice as well and this is what top showed me: You can see the 5 threads we specified in the Thread Group taking up 5 apache processes.
  9. Interpret the results Tests are worthless without interpreting the results. So, what the heck does this graph tell me? Pretty good documentation can be found here. Basically, given the load scenario we have setup, my slice can handle ~643 requests/minute or ~11 requests/second. I am not sure what kind of numbers I should be getting but these seem pretty good to me. One last thing to note is that JMeter is not a web browser so these metrics don't include rendering time or execution of any JavaScript.
Overall, JMeter seems to be a great open source tool to test different kinds of load on servers. I look forward to trying it out at work. One last thing I came across is JMeter integration with your Ant build process. Check that out here. I would like to hear about other people's experiences with JMeter, too.

Prior work experience not needed?

Jeff Atwood just posted an article on the myth that the more years of experience a developer has, the better candidate they are for a position. In the article he references a previous post that spoke to the hypothesis that there is no correlation between skill in programming and experience. This is exactly what I was thinking when I wrote my reaction to disillusioned young IT workers. I'm still early in my career and I've tried to stay on a career path that is driven by what I enjoy doing, which is hacking away at code. At the same time, I am not blind to the fact that companies do look for work experience in specific areas. This certainly helps you get your foot in the door. One thing I've struggled with is how do you make the transition into getting that sought-after experience? While I have programmed in a number of different programming languages, these experiences are based on my own pet projects and curiosity of the languages. On the other hand, my professional experience can be summed up as a Java developer. I've been working with Java since I got out of school. While I think working with Java is great since I feel I can be productive in it and there are plenty of career opportunities, the IT industry evolves over time and we see other languages gain traction. I don't have any hard statistics, but I suspect the number of core programming languages an average developer extensively works with throughout their career is probably around 10-12. If you count all the supplemental languages that come with working in certain languages, like HTML, JavaScript, or SQL, this number is probably closer to 20. That sounds like a reasonable guesstimate and if true, I've got a long way to go. This got me thinking about how do I continue to learn if my day-to-day is limited to one programming language. Here's some advice I have for other Java developers.
  • Follow open source - open source projects are a great way of getting exposure to a lot of the Java/JEE platform. The Java platform is a really big environment to be playing with. Open source has provided baselines for everything from database ORM projects like Hibernate/iBatis to MVC frameworks like Spring MVC/Struts to messaging infrastructure with ActiveMQ/Mule to web services with Xfire/Axis2. There is a lot to be learned and I never see a job description for Java developers without some mention of a Java open source project.
  • Change the focus - What I mean here is change what you are doing most of your work relative to the system. At my first job, I mainly worked on the front-end so it was all HTML/CSS/JSP and Controllers. After awhile, I was interested in doing more of the back-end and building out infrastructure with DAOs and web services. At my current employer, I started off again on the front-end. Luckily, it was with a different MVC framework so there was good exposure there. More recently, I've had the opportunity to work on infrastructure and I've been exposed to about five new technologies I never worked with before.
By doing this, I've gained a lot of experience in a short amount of time with respect to working in Java. Basically, it allowed me to get more in-depth experience with Java by using Java in different contexts. This is a great start and if I was planning on working with Java my entire life, I could always continue down this path but that's not reasonable. HR departments love to see previous experience and it reminds me of the catch-22 that recent college graduates face. They want a job but the employer wants prior experience. They can't get experience if the employer doesn't them a job. I would love to hear from people who have worked with multiple programming languages and made the language transition between jobs. If a company had a .NET position or a Rails position and you never had experience in the language, what made the company hire you and allowed you to beat out other candidates that probably had more language experience than you? What inspired you to make the paradigm shift? What advice do you have for others developers with language-limited experience?

Social Matchbox DC

Last week, I attended Social Matchbox DC with Brent and Brendan. We all thought it would be a showcase of startups around the DC talking about the cool things they are doing. To our surprise it was more of a job fair than a social gathering. However, they had free pizza so I can't complain too much. Still, it's refreshing to see there is a startup community in the DC area, where it seems like everyone and their uncle work for the government. Clearspring and Freewebs were both there. I tried out making a widget on Clearspring's platform and making a web site using Freewebs a while back. Both are very cool companies. Although the DC area is more of a Government Valley, I wish there were more venues that allow startups and hackers get together around the area.

Puzzle - 100 Doors

I'm a big fan of logic puzzles. Normally, we only get asked these kind of questions during interviews but they are pretty fun to think about outside of an interview setting. Here we go: There are 100 doors in a long hallway. They are all closed. The first time you walk by each door, you open it. The second time around, you close every second door (since they are all opened). On the third pass you stop at every third door and open it if it's closed, close it if it's open. On the fourth pass, you take action on every fourth door. You repeat this pattern for 100 passes. Question: At the end of 100 passes, what doors are opened and what doors are closed? Snaps if you can figure it out. (No googling allowed!) Update: See answer below:
So, there are many ways to approach this problem. Here's how I went about solving this puzzle. There are two states a door to be in, opened or closed. On each pass of a door, the door's state is toggled. Since all the doors starts off closed, we can say if we visit a door an even number of times, the door will be closed. If we visit the door an odd number of times, it will be opened in the door. Let's see this in action with 5 doors (O = Opened, C = Closed)
Pass # Door 1 Door 2 Door 3 Door 4 Door 5
Initial C C C C C
Pass 1 O O O O O
Pass 2 O C O C O
Pass 3 O C C C O
Pass 4 O C C O O
Pass 5 O C C O C
One thing to note is once we pass door X X times, we never will have to toggle door X again. For example, once we pass door 10 on the 10th pass, on the 11th pass and subsequent passes, we will never have to revisit doors 10 and all the doors before 10. Looking at the 5 doors shown in the table above, we see that only door 1 and door 4 are left open. They will remain open for the rest of the passes to 100. What's special with 1 and 4? What makes us visit a door an odd number of times versus an even number of times? Let's look what made us close door 2, 3, and 5 and open 1 and 4. On the first pass, we opened all of the doors because it was the 1st pass. Here we know door 1 is going to remain opened. On the second pass, we closed all of the doors with numbers that were even or divisible by 2. (doors 2, 4, 6, 8, etc) Here, we know door 2 is going to remain closed. On the third pass, door 3 gets closed and remains closed. On the fourth pass, door 4 gets reopened and remains opened. On the fifth pass, door 5 is closed. The factors of 1 are 1 and itself. It has one factor The factors of 2, 3, and 5 are 1 and themselves. They have two factors. The factors of 4 are 1 and itself, as well as 2. 4 has three factors. Didn't we say if we visit a door an odd number of times, it remains open? It turns out the number of factors a number has is the same number of times we visit it. If a number has an odd number of factors, we visit it an odd number of times. If a number has an even number of factor, we visit it an even number of times. So, the big question is what numbers have an odd number of factors? Looking at 1 and 4 gives us some insight. Both numbers have factors that are performing double duty. 1 has 1x1 and 4 has 2x2. While factors come in pairs, we only count these factors that are performing double duty as one. What do we call numbers that have factors that perform this double duty? Perfect squares. The answer is doors 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 are opened. The rest are closed.