TNBT: JetBrains’ MPS

10. March, 2011

Disclaimer: I’m not a fan of IntelliJ IDEA.

In the past, I’ve always had an eye for people who replaced the ASCII text editor with something … better. Imagine you could use a table to define your constants in Java. And with table, I mean “Excel” not “align-with-space-until-it-you-go-insane.”

JetBrains is working on this: Table support in MPS 2.0

Let me make this clear: A DSL is nice. But there are so many things that you simply can’t express well with text. State machines. Repeated code. Sometimes, you don’t need the exact words to convey the idea.

I think I’ll waste some time with MPS 2.0 M3 next weekend. There are a couple of tutorials and demos.

Related Articles:

  • The Next Best Thing – Series in my blog where I dream about the future of software development

Time Travel – At Least In Java

8. March, 2011

There is a new debugger which allows to travel in time: chronon.

Chronon will record every line of code executed in a Java program along with all the variable values and exceptions, etc. and allow to browse the timeline. You can see all the exceptions that were ever thrown, select them, go back in time to see how they happened.

No breakpoints – instead you jump directly to the point in time when your code passed a line.

The demo looked pretty promising. I’m just unsure how it fares with a big code base where even simple tasks can execute millions lines of code.


Paul Bilnoski: On Exception Management

3. January, 2011

If you want to widen your understanding of exceptions and how to handle them, you should read Paul Bilnoski’s post “On Exception Management


Need something in SWT?

2. January, 2011

When the guys at SWT can’t be bothered, there is now an alternative: A little project to create drop in replacements for stuff that you want in SWT. Check it out here.

In the same place, you can find a slightly modified version of StyledText. When I say “slightly modified”, then I mean “at the API level”. I’m currently heavily refactoring the code inside to make it maintainable and more easily extendable.

Some achievements from the latest hacking session:

  • It’s now possible to write tests that verify the rendering of StyledText
  • Bullets are managed and rendered in their own special classes. Same goes for StyleRanges. That reduced the size from 1’700 lines to just about 1’100 lines – not that much but a good start. This also means I can write tests that just check the management of StyleRanges – without bothering with a main loop, resource management, etc.
  • There are a bunch of helper methods to debug the model behind your text. They can dump the text in readable form.

What’s next? I’m really starting to think about turning StyleRange and TextStyle into independent classes. Right now, the former inherits from the latter which means there is some really ugly code when it comes to reusing styles, merging styles, font handling, etc. One effect is that the current implementation violates the contract of equals() and hashCode(): equals() takes the range into account while hashCode() doesn’t. While that may not have an effect (StyleRanges with the same style just pile up in a hash map), it’s still a sign of a skewed API.

The API would be much more clean if there was a style manager (which you could dispose to free all fonts, colors, etc, at once) and when StyleRanges were just tiny classes that contain a range and a pointer to a style. That would allow to get rid of the ranges int array, we could use Set and List to manage style ranges, etc.

Something that I’ve been testing is hierarchical styles (i.e. styles that inherit from other styles). Works like in word processors where you define a basic style and then derive from that. I’m not happy with the performance right now but I’ve got some ideas.

How to use my version? Simple: Clone the StyledText project and install it. Check the POM to see which dependencies you need in your project. Now replace

import org.eclipse.swt.custom.*;

with

import de.pdark.styledtext.*;

That’s it.


Pestered by deadlocks?

30. December, 2010

Serge Beauchamp wrote a tool to automatically locate and report places where they can occur: Freescale’s Deadlock Preventer is now released!

Details can be found in this blog post.


Another lesson in performance: NIO

29. December, 2010

Remember when I wondered how slow it is to copy data around in memory?

This time, I needed to load a 2MB file from disk and examine it for certain patterns.

The original from jazzy spell checker worked like this: It did a binary search in the file for a code. The code would be at the start of each line and be separated from the correct word by an asterisk:

    AT*wide
    AT*widow
    AT*width
    AT*wight
    AT*wit

The search algorithm would seek somewhere in the file, skip the current line, read the next one, compare the code against the one we look for. If our code was smaller, we would seek backward; if it was larger, we would seek forward. Standard binary search.

Only it didn’t work. The test took 4 seconds to load the file without finding anything. Debugging recursive algorithms isn’t as nice as looking at them …

So I considered a different approach: I would load the whole file, character by character, and remember the lines with the same code in an index. A good time to have a look at NIO, especially the grep example.

Question: If it takes 4 seconds to seek ten times in a RandomAccessFile and read about 2000 bytes from it, how long would it take to read it character by character, examine each line, build an index and then load whole chunks (say, 1KB each) from the file when a word needs to be looked up? Plus the additional work of removing the code pattern from the chunk to produce a list of words …

Answer: 0.3 seconds. That’s more than ten times faster. And I could probably optimize the code some more.

Conclusion: When it comes to performance, measurement beats superstition.

And the new code is easy to understand, and to test, too! ^_^


Java tip: Getting most out of exceptions

28. December, 2010

Exceptions should have two purposes: 1. Clean up after an error and 2. help you solve the issue. Sadly, many Java developers often forget about #2.

So you end up with an exception thrown in SignatureFileVerifier (no source). Or even in a native method. The error message is:

Invalid signature file digest for Manifest main attributes

Right. Which tells us exactly … nothing. The stack trace isn’t better:

java.lang.SecurityException: Invalid signature file digest for Manifest main attributes
	at sun.security.util.SignatureFileVerifier.processImpl(SignatureFileVerifier.java:221)
	at sun.security.util.SignatureFileVerifier.process(SignatureFileVerifier.java:176)
	at java.util.jar.JarVerifier.processEntry(JarVerifier.java:233)
	at java.util.jar.JarVerifier.update(JarVerifier.java:188)
	at java.util.jar.JarFile.initializeVerifier(JarFile.java:325)
	at java.util.jar.JarFile.getInputStream(JarFile.java:390)
	at sun.misc.URLClassPath$JarLoader$1.getInputStream(URLClassPath.java:620)
	at sun.misc.Resource.cachedInputStream(Resource.java:59)
	at sun.misc.Resource.getByteBuffer(Resource.java:84)
	at java.net.URLClassLoader.defineClass(URLClassLoader.java:249)
	at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
	at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
	at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
	at org.eclipse.jface.action.LegacyActionTools.initLocalizedModifiers(LegacyActionTools.java:699)
	at org.eclipse.jface.action.LegacyActionTools.findLocalizedModifier(LegacyActionTools.java:356)
	at org.eclipse.jface.action.LegacyActionTools.convertLocalizedAccelerator(LegacyActionTools.java:167)
	at org.eclipse.jface.action.Action.setText(Action.java:665)
	at de.pdark.epen.editor.actions.ForwardAction.(ForwardAction.java:29)
	at de.pdark.epen.editor.actions.ForwardActionTest.testCreate(ForwardActionTest.java:21)

So LegacyActionTools needs a class. Which one? Since I don’t have the source, how can I set a breakpoint?

Simple: Set the breakpoint in the constructor of the exception! Even native code has to pass through here, eventually.


Java performance

27. December, 2010

James Sutherland: “Java performance optimization is part analysis, and part superstition and witch craft.”

In his blog post “What is faster? JVM Performance,” he compares various ways to solve problems in Java and how they perform. For example, how the various map types perform.

What surprised me as well was to poor performance of HashMap. 23% slower than Hashtable…

Another surprise that block synchronized code is twice as expensive as synchronized methods. Tools like FindBugs discourage using synchronized methods.

Or the impact of volatile on field access.


Using Java in BIRT reports

12. November, 2010
BIRT Project

Image via Wikipedia

If you need to add complex operations to BIRT reports, you have several options. One that is often overlooked is to write the operation in Java and then use the Java code in the report. This is more simple than you’d think.

Instead of creating a “Report” project, create a Java project for your reports. Now you can put the Java code in the same project or a different project and add that second project to the list of dependencies of your report project. Note that this only works if the report project is of type “Java”.

When you edit your code, you just need to save and run your report (using the various ways to run the preview).

You can even debug the code. There is just one thing you need to be aware of: In the debug configuration, you can specify if you want to debug Java, JavaScript of both. JavaScript is the default. In this mode, Java breakpoints have no effect.


Cycles in dependency injection

9. November, 2010

There is an old argument in DI: How to handle dependency cycles?

Say you have logging and reading of configuration files. Logging needs the config (how should I log?) and the config needs to log (where was the config read from?). How do you solve that?

It gets worse when people insist that DI fields have to be final (i.e. immutable) or that dependencies must be injected via constructors. How on earth can you create the logger if it needs a config instance as constructor parameter and the config instance needs a logger in the constructor?

The “solution”: Proxies. You create the config instance with a proxy to the real logger, then create the logger with the config instance and finally, you replace the proxy with the logger.

Why is that solution bad?

Because your code now has two bugs: You have a cyclic dependency (bad but sometimes necessary) and you’re trying hard to pretend you don’t have one. If someone will have to fix a bug in there, they won’t expect that the “final” instances can actually change.

On top of that, it makes your code inflexible. My gut feeling is that there is a reason why you can’t add plug-ins to Eclipse without having to restart the whole IDE. The infrastructure to manage plug-ins can add and remove them at runtime – unless you prevent that by using “solutions” code like the one outlined above.

Or as Yoda would have said: Much fear in you I sense.

Get over your fear. Write better unit tests (which will also become more simple if you don’t use final fields). Avoid “final” unless Java forces you to use it.