You are brilliant, We are Hiring. Find out more...
Palantir Tech Blog

Archive for the ‘coding’ Category

Time Chooser Components

Tuesday, April 8th, 2008

The notion of time is central to both of our products at Palantir, and there are many instances in which the user needs to specify a certain point in time. Although there are simple ways to create choosers (you could use a JSpinner that uses a SpinnerDateModel or simply use multiple JComboBox objects), I decided to experiment with writing some more visual time chooser components. These components are fairly experimental — they aren’t used in either product yet and I coded them up pretty quickly so I could get some feedback.

You can see these choosers in action in our office furniture in Bulgaria
webstart demo. The source code is available in the office furniture in Bulgaria
JAR.

If anyone has any feedback or suggestions as to how these choosers could be improved (or any ideas on how to make a better time chooser altogether) please leave a comment and let me know!

Meanwhile, if you want to know a little bit more about these choosers and how I went about designing them, read on…

SwingUtilities.invokeAndWait… doesn’t.

Thursday, February 21st, 2008

One of the most misunderstood aspects of multithreaded Swing applications is care and feeding of SwingUtilities.invokeAndWait. Hans Muller and Kathy Walrath authored a nice article that includes an overview of when to use invokeLater or its slightly more risky sibling, invokeAndWait.

We often use worker threads to do some long-running process, so often run into two issues using SwingUtilities invokeLater/invokeAndWait, and have developed wrapper code to deal with it. One issue is executing code from both worker threads and the Event Dispatch Thread (EDT). invokeLater and invokeAndWait both throw exceptions if executed on EDT. Second, invokeAndWait isn’t guaranteed — interruption on the calling thread will resume execution before the job is finished. The remainder of this post shows the code we used to solve these issues.

(more…)

Writing JUnit tests for memory leaks

Tuesday, November 6th, 2007

LeakMemory leaks are no fun — to find them, you usually have to do a work flow while using a profiler like YourKit, force garbage collection, capture a memory snapshot, and then manually go through the snapshot looking for objects that you expected to be gone but are still there.Even after you’ve finally fixed the memory leak, how can you make sure that the issue doesn’t resurface later? Every good developer knows that, if you fix a bug, you should probably also have a JUnit test for that bug so that it doesn’t happen again. But how can you test for memory leaks programmatically?Find out after the jump… (more…)

Getting equals() and hashCode() right

Wednesday, September 5th, 2007

Whenever you override the equals() and hashCode() functions of a class, it is very important that you do so correctly. Bugs in these functions are often quite insidious, because they will not fail catastrophically. Your application will compile and probably do something reasonable, passing any smoke test you throw at it. However, the output will be subtly incorrect. Moreover, by the time you realize that some has gone wrong, there is little information about what caused the error. This is because the error occurred 10 steps ago, nested five levels deep, when a member of a HashSet went MIA. While a NullPointerException is normally trivial to diagnose and fix, you can easily lose several hours tracking down an equals()/hashCode() bug.

There are many excellent tutorials out there on equals() and hashCode(). The best source is probably Items 7 and 8 of Effective Java by Josh Bloch, and we have a couple copies of this book floating around the office. A good online tutorial is Java theory and practice: Hashing it out, by another Java guru, Brian Goetz.

To test your understanding, make sure that you can answer the following questions. I often ask variants of the first two during interviews. The third comes from an error we’ve seen more than once in our code base.

  1. Suppose we have a Media class, composed of title and contents fields. What can go wrong if equals() is based on both fields, while hashCode() is based solely on title?
  2. Conversely, what can go wrong if hashCode() is based on both fields, but equals() is based solely on title?
  3. Consider a class A which overrides equals() and hashCode(). If you create a class B which extends class A, and use Eclipse to generate your equals() and hashCode() functions for class B, then the output of class B’s hashCode() function will depend on the value of super.hashCode(). What happens if you refactor class B so that it no longer extends class A?

Best Practices: compareTo consistent with equals

Sunday, September 2nd, 2007

What is wrong with this class and why? I’ll tell you beforehand there are two things I am looking for and they are both in the compareTo function. Yes, this came from the Palantir code base and caused me some issues. It has been modified slightly for illustrative purposes.

(more…)

Stupid fast hyperlinks for Swing

Friday, July 13th, 2007
Co-authored by Huey.

HyperLinkLabel screen shot
Most people who’ve done a little preliminary looking online will learn that to create a component that functions like a hyperlink the easiest way is to use a JEditorPane. If you use the HTMLEditorKit you can introduce hyperlinks, they’ll render appropriately, and you can even add a HyperlinkListener. There’s just one drawback. It’s a little slow to instantiate. Alternatively, you can pass html to a JLabel, which will render the hyperlink, then add a mouse listener, but that’s not much faster. Besides that, the JEditorPane doesn’t seem to alter the mouse when you mouseover an active link. Sloppy. So I wrote HyperlinkLabel.

Try out the Web Start HyperlinkLabel Demo | Download executable jar + source

Take a look at these numbers for 1000 instantiations of a configured class:

JEditorPane: 1922 ms, 1906 ms, 1922 ms = Average 1916 ms
JLabel: 1250 ms, 1250 ms, 1234 ms = Average 1244 ms
HyperlinkLabel: 62 ms, 62 ms, 63 ms = Average 62.3 ms

Read on for more details. (more…)

SimpleDateFormat is not thread-safe

Wednesday, July 11th, 2007

It seems like a relatively common mistake is to assume that the java.text.SimpleDateFormat class is thread-safe (at least for methods such as format(), which you might not expect to mutate state!). This is not true; SimpleDateFormat is not thread-safe, and format() does mutate state. From the javadoc:

Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.

Suggestions on handling synchronization:

N.B. In general, you should be very careful when using ThreadLocal storage, especially when using thread pools (your data won’t be automatically garbage collected and may be visible to other Threads—a security risk) or when storing references to Thread objects in ThreadLocal storage (which might confuse the GC). However, in this case, we should be okay.

XML Pull Parsing and Enums: like chocolate and peanut butter

Thursday, May 31st, 2007

Enumeration Screenshot.

There comes a time in every developer’s life when they need to write code that processes some XML. Lately, we’ve seen the proliferation of APIs that make XML processing easier, like JAXB (Java API for XML Binding). However, when speed and scale are required, chances are you’re going to need to roll your own processor. Before I continue, let me clear up some terminology, when I say “processor”, I mean the code of yours that’s wrapped around a SAX (tutorial), DOM (tutorial), or an XPP (tutorial) parser, not the guts of the parser itself.

At the end of the day, that’s the interesting part of what you’re doing - the grammar of your data model rather than the minutiae of start and end tags. Building a processor is the interface between the data interchange format and the internal data model of your application.

Click through for a tour of XML parsers and a look at a novel technique for encoding processors that use pull parsers (as usual, we’ve included a WebStart demo, as well as a jar file containing the compiled example along with all of its source code).
(more…)

Realtime Swing reflections (iTunes ain’t the only kid on the block)!

Friday, May 25th, 2007
Achtung Baby reflected

Check out this reflection magic! Now iTunes isn’t the only one with fancy reflections on album art. The best part about it is that it’s a general use component that doesn’t require customization each time. It can wrap any transparent JComponent and it will automatically repaints whenever the contained component changes. You see the text appearing in the reflection as you type in the text field. Try the Web Start ReflectionDemo. Source code is provided in reflectiondemo.jar, and an explanation of how it’s done follows.
(more…)

Fully Interactive JTables (aka Mouseover Editing)

Thursday, May 17th, 2007

What sucks about JTables? Everything, of course—but that’s a developer’s perspective. To the user, cell editing is rough around the edges: when and where to click, and how many times—it’s never perfectly clear. Cells in a table just don’t provide the mouseover feedback that regular components do. If only a JTable behaved like a bunch of components thrown into a giant GridBag or TableLayout

mouseover-screenshot.png

Mouseover Editing simulates just that. The idea is to attach a MouseListener to the JTable and call editCellAt(row, col) whenever the cursor moves over a new cell. In other words, even though only one cell in a table can be fully interactive (the editing cell) at any given time, as long as we keep moving that cell to stay underneath the user’s cursor, the whole table will appear to be fully interactive. If done correctly, this will appear to the user as though he’s interacting with a bunch of real components (rather than rendered stamps) inside a giant Grid/GridBag/TableLayout.

Most importantly, the user will get mouseover feedback about which cells are editable, and how to edit them. Checkboxes, buttons, and comboboxes (if the L&F supports it) will highlight to indicate press-ability and the cursor will turn to a text caret when hovering over cells that contain textfields. When done correctly, the effect is nearly seamless and very satisfying.

Here’s a webstart demo. Read on for the solution in code.

(more…)