1 2 Previous Next

enicholas

25 posts
enicholas

Introducing Java CSS Blog

Posted by enicholas Jul 17, 2008

How people configure Swing today

If you've ever written a non-trivial Swing program, you've probably written code that looks a lot like this:

JSlider slider = new JSlider(0, 100, currentValue);
slider.setMinorTickSpacing(5);
slider.setMajorTickSpacing(25);
slider.setPaintTicks(true);
slider.setForeground(DEFAULT_FOREGROUND);

That's an awful lot of configuration for one component, and worse: it's all compiled code, and therefore relatively inaccessible. The more experienced programmers in the audience are going to immediately (and quite rightly) complain about the setForeground() call -- that should be installed into the UIDefaults table -- and we should probably be using constants instead of those magic numbers.

But then we, in a sense, end up with an even bigger mess. Some of the slider's configuration comes from the UIDefaults table, some comes from constants defined well away from the slider itself, and some (like setPaintTicks(true)) is still buried directly in the slider's initialization code. And we still haven't fixed the real problem, that all of these values are still stored in compiled code and therefore not easy to get at or change.

Even-more-experienced coders will now suggest another change -- that we put the constants into a configuration file of some kind, rather than into code. So we perhaps write a configuration file containing something along the lines of:

default.font              = Dialog-12
default.foreground        = #000000
mySlider.minorTickSpacing = 5
mySlider.majorTickSpacing = 25
mySlider.paintTicks       = true

Problem solved! Right? Well, sort of. You've still got to write code to process this configuration file. You've got to work out how the values defined in the file actually get applied to components.slider.setMinorTickSpacing(getProperty("mySlider.minorTickSpacing"))is simple, but lame -- what happens if you add a new property to the configuration file? Unless you're specifically looking for it, it won't be respected. So you might go all the way to the logical extreme of using reflection to apply these properties by dynamically finding the relevant mutator methods.

I've seen configuration files along these lines (though the details of course differ) in many different Swing programs, and I don't think they're uncommon. I've written some myself. But there's a real problem with this approach -- you're reinventing the wheel. What you've created is in effect a very simple and limited stylesheet language. And if you're going to do that, why not just use a real stylesheet language?

Using CSS instead

There already exists a powerful, flexible stylesheet language that millions of people are familiar with. It's called CSS, and various (mostly very poor) implementations already exist for Java. With a proper CSS engine, you wouldn't need to bury the configuration in your code or burn it into proprietary configuration files. The configuration above might be expressed as:

* {
  font: Dialog-12;
  foreground: black;
}

JSlider#mySlider {
  minorTickSpacing: 5;
  majorTickSpacing: 25;
  paintTicks: true;
}

Admittedly, in this simple example there's not a clear benefit to using CSS instead of a proprietary file -- the syntax is a bit different, but the two files are about equally complex. The real benefit of CSS comes from all of the additional power it offers.

Want to only affect sliders which appear under MyColorChooser? No problem, use the selector "MyColorChooser JSlider". Or pick every label serving as a title with"JLabel.title". What about JButtons, but only when they are moused over? Use "JButton:mouseover".

What about even more complex selectors, such as "JSliders which are direct children of a MyPanel appearing in the currently active window, but only when they are set to their maximum value"? No problem, with a slight syntax extension "Window:active MyPanel > JSlider:{value == maximum}" does just the trick.

The Java CSS Engine

I mentioned above that the existing CSS implementations for Java are generally very poor. That's why I ended up creating a new one, which (hopefully) far exceeds previous CSS engines in many respects.

Click the launch button to see a simple demo of my CSS engine:  

 

For comparison, here is the exact same application without a stylesheet:

 

The demo application also includes a stylesheet editor window, which allows you to update the stylesheet or turn it off altogether:

 

The stylesheet specifies some interesting rules, such as

JSlider#tip:{value <= 10} {
  background: red !over 0.3s;
}

The JSlider#tip portion of the selector means that this rule only applies to the JSlider named "tip". Okay, simple enough. The next part ":{value <= 10}"is what is called a programmatic pseudoclass -- basically just a boolean expression which controls whether or not the rule applies, taking the form of an EL expression evaluated using Beans Binding. So this rule applies only when the slider has a value of 10 or less.

One other unusual feature of this rule is the !over 0.3s expression. This signifies an animation, happening over a period of 0.3s. Try dragging the slider left and right to see the "good tip" and "bad tip" animations fade in and out. (Please note I'm not actually passing any judgment on tips. This is just a stupid demo. I suck at demos.)

Conclusion

Java CSS is a powerful, flexible engine for styling Swing components, supporting very powerful selectors, tons of pseudoclass states, and advanced features like animated state changes.

For full documentation or to download Java CSS, please visit theJava CSS Home Page.

I know, I know, it's been far too long since I've made an entry. My younger son is ten months old now, so I suppose I should probably stop using "new baby" as an excuse for my laziness... Ahem. Before I joined Sun, I thought I knew a lot about Java. I had been using it for a decade and had dug into its innards more times than I could count. Anytime I ran into inexplicable Swing weirdness or whatnot I wouldn't hesitate to dive into the JRE's source code and study it, or even recompile the classes with my own diagnostic code added. I wrote my own classloaders, I manipulated bytecode on the fly, I even wrote my own compiler for a JVM-targeted language. I had earned the right to call myself a guru. Or so I thought. Joining Sun nearly two years ago was a humbling experience. You see, it turns out that knowing a lot about Java works as a third-party developer is very different than, say, having to figure out how to rip the JRE apart and reassemble it on the fly without running programs noticing (Java Kernel, for the uninitiated). I have had to learn more about Java's inner workings than I ever really wanted to know, and maybe you'll find some of it interesting. Towards that end I'm going to pick a couple of random topics to blather about here, with the intent of hopefully making this a semi-regular feature. 

Why can Java Web Start specify JRE versions, but the Java Plug-In can't?

If you have worked with both JNLP programs and applets, you are no doubt aware of the incongruities. JNLP programs can specify which JRE version they need to run with, their memory settings, command-line arguments, and so forth. Applets, on the other hand, are stuck with whichever JRE is registered with the web browser, and have no control over any JRE settings. (JRE Settings can be changed via the Java Control Panel, but cannot be specified by or for individual applets.) The limitation arises because the JRE which handles applets runs inside the web browser. It lives within the browser process and address space, and as far as the OS is concerned is merely another chunk of the browser's code, just as with any other plug-in. And you can't simply load more than one JRE into the same OS process, because they would have conflicting symbol definitions, entry points, and so forth. It would be like trying to boot two different operating systems on the same computer, without the benefit of (very sophisticated) tools like VMWare. To fix this, you've got to run the JRE in a separate process, but have the applets appear within the web browser window. This, of course, introduces all sorts of challenges and requires some clever engineering, but fortunately people smarter than me were assigned to the task. A group led by Ken Russellhas done just that, resulting in what is officially (and wordily) named Next-Generation Java
enicholas

Java Kernel Unmasked Blog

Posted by enicholas May 24, 2007
In my last entry, I briefly introduced the major features of the upcoming Consumer JRE. I'd like to now go into details on my pet project, code-named Java Kernel. 

Overview

As previously mentioned, the idea is to create a 'minimal' JRE which has enough code to run System.out.println("Hello world!") and... well, that's about it. Every class or native library that isn't strictly necessary to boot up the JVM is excluded. This minimal JRE has a few tricks up its sleeve, of course. It can detect when you try to access a class, such asjavax.swing.JFrame, which isn't currently installed. It will then go download and install a "bundle" containing the required functionality. As far as your program can tell, nothing unusual happened -- it requested javax.swing.JFrame, it got javax.swing.JFrame. The only real difference is that (due to the required download) the classload took longer than usual. 

User Interface

Naturally, we display a progress dialog for any downloads taking a meaningful amount of time. If you use a freshly-installed Kernel JRE to run a Java program, you'll see a dialog telling you that a few components are being downloaded, and then the program window will pop up and life will continue as normal. You usually won't see any other progress dialogs -- most programs download everything they need before the main window shows up. Even with the ones that don't, Swing and AWT are by far the biggest bundles you will end up downloading, and both of them will be there before the main window appears. The other bundles are mostly quite small and won't involve an objectionable delay (and, of course, if the delay is short enough we don't pop up a dialog at all). Other than this, the Kernel JRE looks and feels exactly like any other JRE. 

Bundles

The Kernel JRE is currently divided into a hundred or so different bundles. These bundles generally follow package boundaries -- if you touch any class in (say) java.rmi, the entire java.rmi package will be downloaded. This means you'll end up downloading more classes than strictly necessary to run your program, but the alternative, downloading classes one-by-one, would be ridiculously slow due to all of the individual HTTP requests involved. We are trying to strike the proper balance between reducing the number of bytes downloaded and reducing the number of HTTP requests made. Some bundles involve more than one package. javax.swing, for example, is entirely useless without javax.swing.eventand several other packages. Since they are so tightly interconnected, they are packaged together into a single bundle. A few bundles don't cleanly follow package lines. Injava.awt, for example, it makes sense to separate out the subset of AWT used by Swing programs. A Swing program isn't likely to touch AWT components like java.awt.Button, so we have a separate bundle (internally named java_awt_core) which includes only the AWT classes that a typical Swing program would use. 

Still not small enough...

We've got other space-saving tricks, as well. Take a look at one of the core, absolutely essential files in Java 6: jvm.dll. This is (obviously) the JVM itself, needed to run all Java code. It's 2.3MB. And that doesn't include any classes, launchers, the installer, the Java Plug-In, Java Web Start, or any of the other essential JRE features. When you're trying to deliver an entire JRE in under 2MB, the fact that one of the required files is 2.3MB puts you at a pretty severe disadvantage. Compression helps, obviously, but it takes more than a good compressor to squeeze things down this small. Java Kernel has its own version ofjvm.dll, which omits a lot of optional features like JVMTI and additional garbage collectors. The current prototype'sjvm.dll is a much more svelte 1.1MB. And when the Kernel JRE finishes downloading itself in the background, it will swap in the good old full client JVM, so you won't be without these optional features for long. 

Background Downloading

The Kernel JRE will continue to download its missing bundles in the background, whether they were specifically requested or not. Over a broadband connection, this will only take a couple of minutes, so the window of time during which you might run into missing bundles is brief. After the last bundle is downloaded, the Kernel JRE will reassemble itself into an exact replica of the "normal" JRE. All of the disparate bundles will be repackaged into a unifiedrt.jar file, the Kernel JVM mentioned above will be replaced with the traditional client JVM, and so forth. A "finished" Kernel JRE will be byte-for-byte identical to a "normal" offline JRE. 

But what if I want to pre-download everything I need?

The single most frequently asked question is "Can I force the Kernel JRE to go ahead and download everything I need, so that there are no pauses or download progress dialogs while my program is running?" I mentioned during my JavaOne session that we were well aware of the need for this, and working on a solution, but that we weren't ready to discuss it yet. I'm pleased to announce that the plans for this have been finalized (well, as final as anything gets in the software industry...) and I can reveal them now. The JDK will include a tool which allows you to assemble a "custom bundle" containing all of the classes and files needed by your particular program. You determine the entire set of JRE classes needed by your program (for instance by running java -verbose or by using a static analyzer) and then use this list to create the bundle. (Command names and options likely to change)> java -verbose -jar MyProgram.jar > class_list.txt > jkernel -create custom_bundle.zip -classes class_list.txt You can then install this bundle into a freshly installed Kernel JRE:> jkernel -install custom_bundle.zip You can run thejkernel -install command as part of your program's installation or startup. With a custom bundle installed, you can rely upon the absolute minimum set of classes and files needed to support your program, and thus get the smallest possible download size. This isn't yet optimal for applets or web start programs, as (unlike standalone programs) they don't have the ability to install the bundle before they start to execute, and thus before any bundles are automatically downloaded. Ideally I'd like the ability to simply specify "And my program needs this custom bundle, also" in the applet tag or JNLP file somewhere -- the only question is whether we'll be able to get this into the first release or not. 

Results

Remember how the Java 6 jvm.dll is 2.3MB by itself? The Kernel JRE's installer includes jvm.dll, the other native files and hundreds of classes needed to boot the JVM, the Java Plug-In, Java Web Start, java.exe, javaw.exe, javaws.exe, the installation code, and various support libraries needed to support the installer (such as unpack200). And it's only 1.9MB. If you build a custom bundle containing the classes required to run a typical Swing program, it comes out to about 1.5MB, for a total download of around 3.4MB for the JRE + custom bundle. Bigger programs might use as much as 4MB-5MB of the total JRE size, but it would be rare to exceed that. Compared to the current JRE's size of somewhere between 10MB and 15MB, depending on how you measure it, hopefully you will agree that this is quite an improvement. So, I'm sure you've got lots of questions for me. Shoot.  
When Steve Jobs announced the iPhone at MacWorld, Mac fans were understandably upset that no other announcements were made. There was nary a mention of Macs, Mac OS X, or iPods -- and disgruntled fans pointed to this as evidence that Apple was ignoring these products. A few of the saner voices in the audience took the stance that since nothing could possibly have competed with the iPhone announcement, there was no point in Apple even trying to talk about anything else until the iPhone furor died down. After seeing what happened at JavaOne, I'm inclined to agree with this particular theory. The "iPhone effect" has struck again -- only this time it's the "JavaFX effect". We announced a bunch of exciting things at JavaOne 2007, but the news of JavaFX has inspired so much coverage and discussion that it's hard for anything else to get any press time. The other big announcement, the one you might not have seen much (or any) coverage of, was the Consumer JRE. The Consumer JRE is a release of Java 6 targeted at making the end-user experience better, meaning smaller downloads, faster installs, better graphics performance, smoother installation, faster startup, better reliability, and a bunch of other nice enhancements. The best part is that I've seen several references to a "rumored" Consumer JRE release. Considering that we publicly announced the Consumer JRE in front of thousands of developers, I think we can safely move this particular 'rumor' into the "confirmed" column. In case you missed my JavaOne session about the Consumer JRE, here's what you should know: 
  • The Consumer JRE will be a Java 6 update release delivered in the first half of 2008.
  • It features performance and usability enhancements geared towards easier, better, faster end-user distribution.
  • Will include the Java Technology Deployment Toolkit, a suite of technologies enabling much simpler JRE detection and installation.
  • The JRE is being modularized, so that bits and pieces of it can be downloaded as needed. In the current prototype, the download needed to support a typical Swing program is between 3 and 4MB.
  • Java Quick Start Service will pre-load portions of the JRE into the system disk cache, substantially decreasing the average start-up time.
  • A new and improved installer will streamline, simplify, and speed up the installation process.
  • Future updates will be delivered in-place -- you will no longer inadvertently end up with fifteen different versions of the JRE on your system.
  • Some of these features may be delivered sooner than others.
I'll go into more details about these specific features in the near future. But for now, at least be aware that the Consumer JRE is anything but a rumor. Also, take note of this poll. Despite the dearth of coverage, it sounds like at least some folks caught the announcement.  
Dieter Krachtus just sent me a link to a project he's working on, a shell extension which allows you to treat JAR files as executable programs under Windows. Now, double-clicking on a JAR file has long caused it to be launched under "java -jar", but with the generic "Java document" icon it doesn't exactly scream "executable program". I'm not sure how many people even know that you can double-click on a JAR to launch it, and between that and the generic icon that probably explains why I've never seen a Java program which took advantage of that ability. With the ability to embed multiple resolutions / color depths of icons directly into your JAR files, as well as Ant integration and a GUI, this looks like a nifty little project. It's currently limited by the fact that it has to be installed on the end-user's system to function, but... what if this sort of capability were integrated directly into the JRE? Is that something you would find useful? It's also worth mentioning that, as a Mac user, I'm used to being able to "install" most applications by simply dragging them to my Applications folder or other convenient location, and "uninstall" them by dragging them to the trash. JAR files potentially represent the same capability offered to users of other platforms -- just download the JAR file, and that is the program, with no need to install it before using it or uninstall it when you're done with it. Just double-click on it to run it, and if you decide you don't want it anymore you merely need to delete it. I think there's quite a bit of merit to this idea. Update: Sorry, I should have explicitly stated that Dieter does not work for Sun and this is not a Sun project -- it's just something I thought was neat. I should also mention that most of the credit goes to Chris Deckers, the project lead.  
enicholas

Grown-up games Blog

Posted by enicholas Jan 8, 2007
My sixteen-month-old son is just at the point where he's beginning to play tag, so it's a part of my day-to-day life now. It's fitting that I find myself tagged by Richard Bair in this grown-up game of tag. In case you have (somehow) missed the meme, bloggers are supposed to reveal five little-known facts about themselves and then tag five more people. So, without further ado: 

Five little-known facts about Ethan Nicholas

  • I ran a BBS (Bulletin Board System) when I was in high school. This was back before the Web existed and before most people had even heard of the Internet. A lovely young lady dialed in using a 1200 baud modem attached to an aging Tandy, I struck up a conversation with her, and eventually we started dating. That lovely young lady is now my wife. (We met before it was cool to meet people online.)
  • I'm a college dropout. During my senior year, GeoCities bought an application I wrote and moved me out to California, so I dropped out of school and never looked back. That's how I ended up at Yahoo!, also -- they bought GeoCities less than a year later.
  • I collect gems and minerals. These are just a few of them (click thumbnails for larger images). All told, I have over three hundred specimens in several different cases. This case is my favorite, because the glass platforms rotate.
    http://weblogs.java.net/blog/enicholas/archive/Case-thumb.jpghttp://weblogs.java.net/blog/enicholas/archive/Cavansite-thumb.jpghttp://weblogs.java.net/blog/enicholas/archive/Goethite-thumb.jpghttp://weblogs.java.net/blog/enicholas/archive/Spinel-thumb.jpghttp://weblogs.java.net/blog/enicholas/archive/Rhodochrosite-thumb.jpghttp://weblogs.java.net/blog/enicholas/archive/Wulfenite-thumb.jpg
  • I turned the attic of my house into a movie theater. I like to play video games up there. The screen in the shot below is 160" diagonal, which is over thirteen feet. I contracted out the actual construction work (framing the walls, hanging drywall, and so forth) but did all of the electronics, wiring, and such myself. It has two rows of four seats each.
    http://weblogs.java.net/blog/enicholas/archive/Theater-thumb.jpg
  • I have a tattoo of a dragon on my left forearm. Everybody asks me if it hurt. Yes, it hurt. It hurt exactly as much as you'd expect getting stabbed with a needle ten thousand times would hurt. My wife has a tattoo on her back, but she said that getting hers "kind of tickled". Evidently I'm a sissy.
So there you go. Five things about me, several of which you would probably have been happier not knowing. And one last thing: Chet Haase, Scott Violet, and Hans Muller, you're it! (Yes, I know that's only three people. And I'm sure they've all been tagged before. But I don't see anything about it in their blogs, so here's hoping they actually produce.)  

Ok, this isn't strictly Java-related, but it's geeky enough that I hope you find it interesting regardless.

Various sites have recently broken the news that the next version of MacOS X, code-named Leopard, will feature support for Sun's ZFSfilesystem. As a Mac user, I find this news particularly exciting, but those of you still using Windows may want to take note as well.

If I sat down and wrote a list of all the things a super-powerful futuristic filesystem should do, completely without regard for practicality or implementation difficulty, not only would ZFS already do everything I came up with, but I doubt I would have imagined even half of its actual features. Suppose you want to clone your hard drive, install a test application, and then roll back to the previous state of your hard drive. How long would that take you? For most of you, long enough that you'd rather just cross your fingers and hope for the best.

Under ZFS, creation of a writable clone of a filesystem is essentially instant. It only has to maintain the difference between the two states, rather than two complete copies of the data, so the clone initially takes no space and virtually no time to create. Once you're done with your tests, destroying the clone is also essentially instant. The ability to instantly create, restore, and destroy snapshots and clones is incredibly powerful and something I'm very excited about, but it's not the only trick up ZFS' proverbial sleeve.

Among other things, ZFS is a 128-bit filesystem, meaning that the total storage it can manage in a single storage pool is 2128 blocks, which is a very big number. In fact, 2128 is such a big number that I'm going to unequivocally state that we will never, ever need more storage than that.

That's a bold claim. Many computational limits have been thought sufficient in the past -- who ever thought we would need more than 4GB of memory in a desktop system? I've seen people making similar claims in response to ZFS, thinking that we've passed every other limit, so why not this one? That's a reasonable question to ask, so let's take a look at how much data a 128-bit filesystem can actually hold.

We need to store a lot of data for this thought experiment, and nothing fills hard drives like video. Let's say it's high-definition video, complete with surround sound -- maybe 10GB / hour after compression. And you record this video 24 hours a day, 365.25 days a year. That's 85.6 terabytes a year, which is certainly a lot of data, but it's well within the reach of modern storage systems. So let's record this video for a very long time, say since the formation of the Earth 4.5 billion years ago. That's an inconceivable amount of data, roughly 359 billion terabytes, and is already more than a 64-bit filesystem can handle.

But what good is only one camera? It might end up at the bottom of the ocean and spend a billion years filming a family of sponges. We clearly need many, many cameras. Let's put one camera for each square meter of the Earth's surface, all of them recording high-definition video for 4.5 billion years. We're up to 2 x 1038 bytes now, an inconceivably large number. You could also express it as 200 trillion trillion terabytes, but that doesn't make it any easier to handle -- it's just too big for human understanding. We must have filled up the filesystem by now, right?

Well, this incomprehensibly gargantuan amount of data has indeed put a dent in our 128-bit filesystem, which is now about 0.1% full. All the data ever produced by the human race -- all speech, books, plays, movies, music, emails, everything -- is a tiny, tiny drop in the bucket in comparison.

A 128-bit filesystem effectively cannot be filled. The laws of physics set an upper bound on the amount of information we can cram into a certain amount of mass and volume, which means that it would take at least 136 billion kilograms worth of matter to hold that much data. And that's just a lower bound on the amount of matter necessary; it might not be a very tight bound (meaning the actual requirement is probably many orders of magnitude greater). Even ignoring the obvious impossibility of creating a storage device that large, you could never create enough data to fill it. Even with a high-definition camera on each square meter of the Earth's surface, it would take almost 4 trillion years' worth of video to fill it.

I think there's a lesson here. Our computers are now powerful enough that it's reasonable to choose limits so large that we can be essentially 100% confident that they will never, ever be reached, not in this universe at least. The question "How large can I imagine this value getting?" is very dangerous, because we humans are creatures of small imaginations. I'm not suggesting that every single limit must be so ridiculously large as 2128, but it's important to remember that arbitrarily chosen small limits have historically been a much, much greater problem than asking the computer to process an extra couple of bytes here and there.

And, because I want to at least mention Java here, take a look at JSR-202, "Java Class file Specification Update". One of the major changes is increasing various limits, because those initially chosen for the sizes of methods and so forth turned out to be too small. The limits of human imagination strike again.

I've been writing Java code for more than a decade now, and there are a handful of methods I've ended up copying & pasting (or, sadly, reimplementing) in virtually every program I've ever written. I'm not sure why these methods in particular seem to keep cropping up again and again, but nevertheless I end up using themeverywhere

send(InputStream in, OutputStream out)

This method takes data coming from an InputStream and dumps it into an OutputStream. This is useful for a lot of different things -- you can take data sent to you by a web server and dump it into a FileOutputStream, you can take the output and error streams of a process and dump them to System.out and System.err, and on and on. 
public static void send(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[2048];
    int c;
    while ((c = in.read(buffer)) > 0)
        out.write(buffer, 0, c);
}
Over the years I've implemented several variations of this basic idea. I've had send() methods that would return the number of bytes they copied, or transfer only a certain number of bytes before stopping, but they've all looked pretty similar. 

readFully(InputStream in)

An extension of the send() method, this takes all of the data retrieved from an InputStream and returns it as a byte array for easy processing. This is potentially dangerous, and should only be used when you know in advance that the data is small enough to comfortably fit in memory. 
public static byte[] readFully(InputStream in) throws IOException {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    send(in, buffer);
    return buffer.toByteArray();
}
An obvious variant of this (assuming a similarly modifiedsend() method) is to fail if the data is bigger than some threshold size limit. 

Character-based variants

The send() and readFully() methods can be trivially modified to work with Reader,Writer, and String instead of streams and byte arrays. 

String replacement

Once upon a time I had a simple method replaceString(String src, String a, String b), which takes a String and replaces all occurrences of sequence A with sequence B. After many RFEs (by myself and others) to include this capability inString itself, along with lots of explanations about how the regular expression features in Java 1.4 did not in fact eliminate the need for this, the replace(CharSequence a, CharSequence b) method was finally added tojava.lang.String in Java 1.5. Now that the capability is in the JRE itself, my ten-year-old replaceString()method has at last been retired for good, and I couldn't be happier about that. Sometimes it's the little things in life... 

What about you?

I've written lots of utility methods, of course, but these are the small handful that I seem to always need no matter what I'm doing. Given my background in client/server code, it's perhaps not surprising that they have to do with data transfer. What about you? Any methods that you just can't live without, that you've been copying from program to program for years?  
Sun recently released a Java security advisory titled Java Plug-in and Java Web Start May Allow Applets and Applications to Run With Unpatched JRE. As with any security advisory, it's important that you take note and ensure that your software is up-to-date -- in this case, the problem is fixed in Java 1.5.0_06 or higher. But a blog entry by the Washington Post's Brian Krebs raises some concerns about this particular security advisory and suggests that merely patching your machine may not be enough. The security advisory admittedly wasn't very clear on this point, but if you have Java 1.5.0_06 or higher installed (which I imagine most of you do by now), you are in no danger from this issue, even if you also have older versions of Java on your system. While that's obviously good news, the fix for this issue may have an impact on some Java developers. If you deploy Java applets or unsigned Web Start programs, keep reading. Java has always allowed you to keep multiple versions installed on the same computer at the same time. Whether you love this particular feature or hate it, there's no denying that it can be useful at times. Certainly as a developer I appreciate being able to have Java 5 and Java 6 on the same machine at the same time, and I know enterprises prefer to be able to certify their internal software against exactly one version of Java without worrying about employees accidentally changing the Java version out from under them. But as with all significant decisions, there is no single right answer. What's right for developers and enterprises isn't necessarily as great in the consumer market, where users would generally prefer not to leave old versions of the software lying around after an upgrade. Unfortunately we can't just suddenly start removing older versions -- because Java hasalways worked this way, many programs depend on this behavior. They may take the Java VM's location and "burn it in" to their launch scripts or registry entries, and removing the specific version on which a program depends would then cause it to break. Various ideas on breaking out of this vicious cycle have been tossed around, but for the time being, this is just the way things work. Unfortunately, it also led to a security hole (again, fixed in Java 1.5.0_06). Sun has always responded promptly to any security problems with Java, quickly releasing a patched version which fixes the problem. But since the previous unpatched and unsafe versions have been left on your hard drive, a malicious program could potentially get access to them. Theoretically, a Java applet could have requested a specific older version of Java and used a known (and long-since patched) security hole in it to compromise your system, even though you had dutifully downloaded the security update. Clearly, this was a situation that had to be addressed. The solution is what is known internally as Secure Static Versioning. Basically it boils down to "untrusted code can't use unpatched older versions of Java". Previously, if you had several versions of Java installed on your system, a program could request one of the older versions in order to exploit it. Now, no matter which version of Java an untrusted program requests, it will receive the highest installed version. The practical upshot of this is that untrusted code will always be run in the most secure Java environment available. Signed, trusted Web Start programs are allowed to request whatever version of Java they want -- they're trusted, so they have full access to your system anyway. Applets (even if signed) will always be run in the latest version. The discrepancy is due to technical differences between Web Start and the Plug-In; I'll go into the details in a future entry. With the quick overview out of the way, let me sum up in an FAQ: 
1. How much danger am I in? If you have the latest JRE (1.5.0_06 or later) installed on your system, none at all. All current JREs include the Secure Static Versioning change, so applets and sandboxed Java Web Start programs are unable to access older versions of Java. If you don't have Java 1.5.0_06 or higher, you would be wise to go ahead and install the latest version. I'm not aware of any exploits "in the wild", but it certainly doesn't hurt to be safe. 2. Do I need to remove old versions of Java? No. Applets and sandboxed Java Web Start programs aren't allowed to access older versions of Java. They don't pose any threat in the first place, so removing them won't change anything. If you do decide to remove older versions of Java, you need to be sure that none of the applications on your computer are using them first. 3. Do I have to change anything about my Java programs? No. If you have a Java applet or sandboxed Java Web Start program, it will always run in the latest available version of Java without any changes on your part. As long as you test your software against newer versions of Java, you shouldn't encounter any problems. 4. What does this mean for standalone Java programs? Nothing. Just like native programs, Java programs which run outside of the Java sandbox already have full access to your system. Requiring them to run in the latest version of Java wouldn't do anything to increase security. 
So, that's that. What might have sounded like a scary security issue (OMG YOU NEED TO UNINSTALL JAVA!!!!11!!!1) turns out to be quite mundane: install the latest patch release of Java and you're completely safe. This is of course great advice no matter what software we're discussing -- you are running with all of the latest patches for your operating system, web browser, Flash Player, and everything else on your system, aren't you? Oh, and while we're on the subject of updates... If you update using Java Update, rather than downloading via java.sun.com, you may find that you don't end up with the very latest update release. That's normal, and it's a result of the fact that Sun distinguishes the latest "consumer version" of Java from the latest "developer / enterprise version". If you go to java.sun.com, you get the latest developer / enterprise version, which is the very latest and greatest code available. If you go to www.java.com or use Java Update, you end up with the latest consumer version, which might be a couple of update releases behind the developer version (but is otherwise identical). In order to avoid swamping end-users with too many updates, only two or three versions of Java a year are made available as consumer versions. Naturally, security fixes (such as the one under discussion here) always warrant a new consumer version, so you're safe no matter how you choose to update your copy of Java.  

"Java Browser Edition" History

Some time ago I proposed the idea of a Java Browser Edition. The basic idea was that the current Java Runtime Environment is simply too big, and most programs require only a small subset of the functionality. The "browser edition" that I suggested would enable you to install exactly the subset of Java that your particular program required, but would be able to download all of the other functionality on demand (and thus be fully compatible with J2SE). I wasn't quite prepared for the response that this entry generated. In addition to generating a lot of comments and further discussions, it ultimately played a role in my getting hired by the deployment team at Sun. I was cautioned by several folks at Sun that the Browser Edition would simply never happen. It would never be approved as a feature in the first place, and even if it were approved, we would never be able to actually pull it off. I'm told that this basic idea has actually been attempted within Sun twice before, and in both cases the resulting size reduction wasn't enough to be worthwhile. The core VM, it seems, is simply too big, and trying to make it smaller is too hard. There has even been a detailed analysisof the idea which paints a rather bleak picture of the potential gains. 

New Name: Java Kernel

The feature did in fact get submitted as a proposal for Java 7, under the name "Java Kernel" (the idea being that you download a small "kernel" of Java functionality, which is in turn capable of downloading the rest of it). And, amazingly enough, it was accepted. And, lucky me, I'm part of the team responsible for implementing it. After having been told that it's been tried a couple of times before and that it's basically impossible -- not a situation which inspires tremendous confidence. 

Building a minimal JRE

The first thing I have to do is establish that this project is feasible. Remember that even though it has been approved, it could alway be un-approved (disapproved?) at any point in the future if things aren't looking good. So I figured I would start out by creating a simple, stripped-down JRE installer that contained only the functionality necessary to run System.out.println("Hello world!"), to get an estimate of the size reduction we could expect. Stripping out the unecessary classes is easy -- you just run Java with the -verbose option to get a list of all of the classes it loads while running the Hello World program. Those classes are all that we need to include inrt.jar. The real problem is the rest of the functionality. My devel build of the Java 6 JRE contains 683 files totalling 119MB. Many of them are not necessary to run Hello World, but which ones? Determining which files were truly necessary and which weren't could be a tough job, so I made my computer determine it for me. I wrote a simple program which would iterate through all of the files in the JRE. It would remove a file and then attempt to run the Hello World program using this stripped-down JRE. If the test succeeded, the file was evidently unnecessary. If the test failed, the file was deemed necessary and restored. After going through all of the files in this fashion, I was left with an extremely minimal JRE that could run Hello World and... well, that's about it. But it at least provided a starting point. Building a working installer from this JRE was itself a challenge, because several of the files that weren't necessary to run Hello World were still necessary to successful install the JRE, but I persevered and now have a fully functioning, minimal JRE. 

Results

I built two JREs using this methodology: one with a program that prints "Hello World" to System.out, and one with a program that displays an empty java.awt.Frame. Here are the results:                
Java 6 Runtime Environment:15.5MB
"Hello World" JRE:2.6MB
java.awt.Frame JRE:3.5MB

Things to note

Before you get excited, remember that this is just an experiment and that the JREs I built aren't the least bit useful. They don't include the Java Plug-In, Web Start, or indeed much of anything, and any "real" program will need at least some of these components. These JREs also do not have the ability to download the missing components, and will simply fail if an attempt is made to access missing functionality. The installers we ultimately ship with Java 7 may well be bigger than this. 

Next steps

Despite the cautions above, I find these results extremely exciting. Keep in mind that so far we haven't done anything the least bit sophisticated -- just omitted unnecessary files and classes -- and we've already gotten the JRE below 3MB for a non-visual program. Classes compress extremely well, so this installer would stay under 3MB mark even with a lot of additional classes included. And there are still a lot of things we can do to improve the size further, such as break up big DLLs to get better granularity. It's hard to say how big the final Java 7 installers will end up being, but my personal goal is to make an installer that can handle basic Java applets in under 3MB. This is a difficult goal, and it may end up being too optimistic, but we're going to get as close as we can. So, what do you think? If the Java installer were 3MB instead of 15MB, would you find the idea of using Java applets (or Java Web Start programs) more appealing?  
I mentioned in my last entry that I have left Yahoo! and am now officially a Sun employee. After an all-too-short break between jobs, my first day with Sun was this past Monday, and it's been quite an experience so far. As with joining any big company, most of my first week was spent trying to get someone to actually set up my access badge and email account, figuring out how to access documentation on various subjects (there is documentation, right?), and dealing with various other miscellaneous getting-started headaches. Most of that is sorted out now and I expect that I should actually be able to, you know, work starting next week. The most exciting part so far has been the fact that I've gotten to be involved in the Dolphin planning sessions we're having this week. I've requested some deployment features in the past, including a gigantic whopper of one, and while I can't give away too many details, I can say that there is definitely some hope. I mentioned wanting an "updatejava.exe" program which would allow you to install specific versions of Java upon request, tremendously simplifying the process of writing installers for Java programs. There's actually a very good chance of such a tool making it into Dolphin, although it would probably have a slightly different name. And lest I erroneously receive credit for this idea, I should point out that this feature was already being investigated before I even suggested it. The "Browser Edition" I suggested in this entry is a more complex problem. When I wrote that entry, I was in the enviable position of being able to request ridiculous improvements and not having to actually write any of the code. As you can imagine, my position is quickly shifting from "Sun should add support for feature <X> right now!" to "Ummm... well... you see, that's a really hard problem and it would be a lot of work...". Regardless, I think it's okay if I reveal that there is a feature more-or-less identical to what I suggested in the infamous "Browser Edition" blog entry currently under consideration for Dolphin. This should not in any way, shape, or form be construed as a promise that we will actually do it-- in other words, don't get your hopes up -- but it's being considered. At the very least, you should be aware that Java applets are the subject of intense scrutiny around here and we are trying to figure out how to improve them, within the limitations of the time and manpower we actually have available to throw at the problem. There's a lot of other neat stuff on the table, most of which I probably shouldn't talk about yet. Hopefully the tidbits I've tossed out so far aren't revealing anything that will get me in trouble... In any case, expect some neat stuff from Dolphin's deployment enhancements. It's also not too late to suggest things: we are definitely interested in your feedback.  
When you work at a major Internet company like Yahoo!, deployment is a Big Deal. You have millions of customers running every version of every OS imaginable, some with marginally working computers, and they all need to be able to run your software. And they need to run it now -- make them wait too long, or download too much, and they'll give up and move on to your competitors. While I'm definitely a huge Java fan, it's a hard technology to deploy to end-users. If a particular user doesn't have Java installed, or doesn't have the right version of Java installed, there are major challenges surrounding the detection, installation, and upgrading process. Even if users have the right version of Java installed, its behavior in web browsers isn't necessary all that reliable. I posted a couple of high-profile rants about Java deployment issues recently, to try to call some attention to these issues. I wasn't really expecting much of a response. I figured some fellow complainers would show up, we'd talk amongst ourselves for a little while, and that would be the end of things. I wasn't expecting Sun to even notice my complaints, let alone actually do something about them. I was happy to be proven wrong. I was asked to put together a resume, and invited to interview with the Java Deployment team. After two rounds of phone interviews and a grueling eight-hour interview process in Burlington, I accepted an offer to join Sun, and will finally have the opportunity to address some of the problems that have been bugging me for so long. This is a really exciting change for me -- to finally be working on Java, instead of justwith it, and to be able to influence where things are headed... well, it's a Java geek's dream come true. Or at least it's this Java geek's dream come true. We're still working out the details, but I should be starting at Sun in about a month. Yahoo! is a great company, and has been very good to me over the years, but this was an opportunity I just couldn't pass up. 

To dispel any rumors...

Before any rumors get started, let me be the first to say that just because I blogged about some deployment ideas does not mean that any of those ideas will necessarily get implemented. Sun obviously found them interesting, or I daresay I wouldn't have been hired, but there's a big difference between finding an idea interesting and actually putting in the time and money necessary to implement it. In particular, don't expect a Java Browser Edition -- much as I would love to see it happen, I'm not naive enough to believe that it's at all likely. I do have a lot of ideas for improvements to the Java Plug-In and Java Web Start; reasonably small, practical features that will nevertheless make a huge difference in how easy it is to deploy Java programs. Hopefully some of them will actually get implemented eventually, but at this point it's far to early to speculate on how things will work out. Rest assured that I will be doing my best to push for easier deployment solutions, and I'm all ears if you have any suggestions of your own. 

What about JAXX?

What does this mean for JAXX, the declarative XML user-interface language I'm working on? In the short term, not much. The position I was hired for has nothing to do with JAXX, and I will still be doing all JAXX work in my spare time, rather than as a Sun-sponsored activity. What about the long term? Your guess is as good as mine. All I know for sure is that I have a lot of ideas for the future of JAXX, and will continue to crank away on it. If the Swing team decides to add a user interface language to Java at some point (which I know they have considered), I expect I would at least be involved in the discussion. Other than that... who knows? 

Looking ahead

The decision to leave Yahoo! was both difficult and painful, but I think I made the right choice. I'm very excited to be joining Sun, and I hope that I will be able to really make a difference. Wish me luck!  
enicholas

All about intern() Blog

Posted by enicholas Jun 26, 2006
Strings are a fundamental part of any modern programming language, every bit as important as numbers. So you'd think that Java programmers would go out of their way to have a solid understanding of them -- and sadly, that isn't always the case. I was going through the source code to Xerces (the XML parser included in Java) today, when I found a very surprising line:com.sun.org.apache.xerces.internal.impl.XMLScanner:395protected final static String fVersionSymbol = "version".intern(); There are a number of strings defined like this, and every one of them is being interned. So what exactly is intern()? Well, as you no doubt know, there are two different ways to compare objects in Java. You can use the ==operator, or you can use the equals() method. The== operator compares whether two references point to thesame object, whereas the equals() method compares whether two objects contain the same data. One of the first lessons you learn in Java is that you should usually use equals(), not ==, to compare two strings. If you compare, say,new String("Hello") == new String("Hello"), you will in fact receive false, because they are two different string instances. If you use equals() instead, you will receivetrue, just as you'd expect. Unfortunately, the equals() method can be fairly slow, as it involves a character-by-character comparison of the strings. Since the == method comparesidentity, all it has to do is compare two pointers to see if they are the same, and obviously it will be much faster thanequals(). So if you're going to be comparing the same strings repeatedly, you can get a significant performance advantage by reducing it to an identity comparison rather than an equality comparison. The basic algorithm is: 1) Create a hash set of Strings 2) Check to see if the String you're dealing with is already in the set 3) If so, return the one from the set 4) Otherwise, add this string to the set and return it After following this algorithm, you are guaranteed that if two strings contain the same characters, they are also the same instance. This means that you can safely compare strings using == rather thanequals(), gaining a significant performance advantage with repeated comparisons. Fortunately, Java already includes an implementation of the algorithm above. It's the intern()method on java.lang.String. new String("Hello").intern() == new String("Hello").intern()returns true, whereas without the intern() calls it returns false. So why was I so surprised to seeprotected final static String fVersionSymbol = "version".intern(); in the Xerces source code? Obviously this string will be used for many comparisons, doesn't it make sense to intern it? Sure it does. That's why Java already does it. All constant strings that appear in a class are automatically interned. This includes both your own constants (like the above "version" string) as well as other strings that are part of the class file format -- class names, method and field signatures, and so forth. It even extends to constant string expressions: "Hel" + "lo" is processed by javac exactly the same as"Hello", and "Hel" + "lo" == "Hello" will returntrue. So the result of calling intern() on a constant string like "version" is by definitiongoing to be the exact same string you passed in. "version" == "version".intern(), always. You only need to intern strings when they are not constants, and you want to be able to quickly compare them to other interned strings. There can also be a memory advantage to interning strings -- you only keep one copy of the string's characters in memory, no matter how many times you refer to it. That's the main reason why class file constant strings are interned: think about how many classes refer to (say) java.lang.Object. The name of the class java.lang.Object has to appear in every single one of those classes, but thanks to the magic of intern(), it only appears in memory once. The bottom line? intern() is a useful method and can make life easier -- but make sure that you're using it responsibly.  
enicholas

The Great Switch Blog

Posted by enicholas Jun 20, 2006
I'm on vacation with my family right now. Vacation time is pretty hard for me to come by -- one of the dangers of being "essential" is that nobody wants to let you leave -- so this is a noteworthy event, made possible only by the fact that I agreed to bring my cell phone and work laptop, ensure the availability of Internet access at my destination, and remain reachable twenty-four hours a day. When we arrived, I got out my laptop and booted it up to check my email. It got as far as showing a blank Windows desktop and then... sat there. Uh-oh. I spent a while fiddling with it, but sadly when your machine won't even boot into Safe Mode and you have no other bootable disks with you, there really isn't much you can do. So here I was, stuck without a functioning computer, when having a functioning computer and Internet connection was part of my vacation deal. A whole week without being able to check email, or read my webcomics, or being able to post blog entries... a whole week without Internet access of any kind. I don't think I can take that kind of punishment, so I did whatever any true geek would do: I used this situation as an excuse to buy a new computer. I (a long-time Windows user) had been lusting after the new MacBooks for quite a while, and my wife was well aware of this. She was also well aware that Fathers' Day was just around the corner, and, well, to make a long story short I love my wife very much and I'm typing this on my new 13" MacBook. Obviously I'm not the first Java programmer to realize that a Mac is pretty great Java environment. When I was at JavaOne, I was shocked at the number of Mac laptops being toted around -- it seemed like every other system was a Mac. But after setting my system up, installing Eclipse, and getting to work on it, I really don't understand how I managed to put up with Windows for so many years. My Mac runs all of the software I need, Java programs run as smooth as silk, and (despite having theoretically less power) it feels faster than my most powerful Windows system. I could spend all day babbling about all of the things I love about it, but one thing is certain: I'm not going back. Oh, and the Windows laptop? I decided to leave it on for an extended period of time, and checked on it periodically. After eight hours, there was still no change, so I went to bed. When I woke up in the morning, I saw that it had actually managed to finish booting. So after somewhere between eight and sixteenhours of sitting there, it finally got to the desktop. I realize that this is pathological -- when your computer takes more than eight hours to boot, something is clearly screwed up and I can't just say "Ha! Windows sucks!", but I sure feel like saying exactly that. I was eventually able to fix it by disabling some startup items... but hey, I got a new Mac out of the deal. Thanks for dying, work laptop!  

(For an introduction to JAXX, start here.)

First things first: JAXX 1.0.1 is finally out. This version contains a lot of bugfixes and significant improvements to the quality and size of the generated Java code. Download it here.

Now that the major 1.0 bugs are fixed and a solid baseline has been established, I'm making plans for the future. Where is JAXX headed? What's next? I've posted a first pass at the JAXX roadmap and am seeking feedback. It's still early and subject to change, and there will be a lot more detail added as time goes on -- but I think it's a fairly decent stab at where things are headed.

I'm particularly excited about the addition of animation, based on Chet Haase's Timing Framework. The first animation features are going to be simple and straightforward, based on the current CSS pseudoclasses. Right now you can use a pseudoclass to, say, make a label turn blue when moused over:

<style>
  #hoverLink:mouseover {
    foreground: blue;
  }
</style>

<JLabel id='hoverLink' text='Mouse over to turn me blue'/>


 

This effect is applied instantly -- the second the mouse enters the label, it turns blue. The initial animation features will allow you to have effects like this be applied gradually over time:

<style>
  #hoverLink:mouseover[duration=500ms] {
    foreground: blue;
  }
</style>

<JLabel id='hoverLink' text='Mouse over to turn me blue'/>


 

Note the [duration=500ms] on the pseudoclass. There will be other properties for controlling acceleration, deceleration, and perhaps other features of the animation. This a simple change, to be sure, but I don't want to go overboard yet. More dramatic animation features will be added in good time.

What else is going on with JAXX? You'll have to take a look at the JAXX roadmap -- just be sure to let me know what you think!

Filter Blog

By date: