Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Thursday, January 14, 2010

Prediction for 2010: VMware acquires Terracotta

While at SpringOne2GX back in October, the thought occurred to me that Terracotta would make a really interesting acquisition target for VMware.  VMware has had some pretty amazing virtualization technology for a while, including the ability to migrate live virtual machines between physical boxes, but it has (as far as I know) all been focused on low-level infrastructural magic.  That changed with their acquisition of SpringSource last year, which followed shortly after SpringSource's acquisition of Cloud Foundry.  Now, if you just add Terracotta to the mix, you could make it possible to easily deploy an auto-scaling clustered app to the cloud.  Doesn't that sound interesting?  Add to that the fact that Terracotta has been a sponsor for at least the last two SpringOne conferences in the U.S., SpringSource and Terracotta have already collaborated to build a sample app, and Terracotta brings Ehcache (easy clustered caching) to the table.  Seems like a potent combination to me.

I have no concrete grounds for this prediction beyond the points above, but I wanted to get the idea out there now just in case it actually happens. ;)

Update (May 26, 2010): Unfortunately, with the announcement of SpringSource/VMware's acquisition of Gemstone, my prediction is now unlikely to occur.  Oh, well.  Plenty of others before me have been wrong. ;)

Monday, December 28, 2009

Handy But Hidden: Collections.newSetFromMap()

I was reminded again today of how much the core Java libraries have grown over the years.  It can be really hard to keep track of all the nice little features that get added in each release.  Today, I was wishing that there was a ConcurrentHashSet class or some other HashSet-style concurrent collection.  Before implementing something myself, I did some searching on Google and found a nice way to solve the problem.  In Java 6 (a.k.a. JDK 1.6), Sun added the utility method Collections.newSetFromMap(), which allows you to pass in an empty backing Map and get out a Set with behavior based on the underlying Map.  So, here is all I needed to do to build a concurrent HashSet:

Set<Observer> observers = Collections.newSetFromMap(new ConcurrentHashMap<Observer, Boolean>());

I also found a bug/enhancement request in Sun's bug database suggesting that this feature should be documented in any core Map for which there is no corresponding Set implementation, such as WeakHashMap and IdentityHashMap.  Given how long I went without knowing the method existed, I wish they'd done it.

Wednesday, August 19, 2009

Interruptible JDBC Statements

I work for a client on a product that makes direct queries against databases via JDBC. A while ago, I added some code so that a user could stop the execution of a series of queries by clicking on a cancel button. Behind the scenes, it interrupts the thread executing the queries. Since that thread checks whether it's been interrupted by calling Thread.currentThread().isInterrupted() before starting to execute each query, no new queries will start once the cancel button was pushed. However, any query that's already started will run to completion before the code discovers that a request to cancel had been made. Recently, my client decided that we should make cancellation more granular and add the ability to stop a query in mid-stream. Looking at the JDBC docs, there's nothing to indicate that any of the relevant methods respond to interrupts (none throw InterruptedExceptions or claim to wrap them in a SQLException), so I had to come up with another way. I settled on an approach where I submit the query as a Callable to an ExecutorService and then block, waiting for the result via Future.get(). If the thread is interrupted while we're waiting, get() throws an InterruptedException, which gives us the chance to call Statement.cancel(). It's pretty simple and works nicely. :)
Here's the code in a somewhat abridged/condensed form (I create the ExecutorService elsewhere using Executors.newCachedThreadPool()):
final String sql = "...<some SQL>...";
final Statement statement = conn.createStatement();
Future<ResultSet> queryFuture =
 execService.submit(new Callable<ResultSet>() {
   @Override
   public ResultSet call() throws Exception {
     statement.execute(sql);
     return statement.getResultSet();
   }
 }
);

ResultSet rs;
try {
 rs = queryFuture.get();
} catch (InterruptedException e) {
 logger.info("Query interrupted - calling Statement.cancel()");
 statement.cancel();
 throw e;
} catch (ExecutionException e) {
 //code to handle or rethrow the exception
}
By the way, if any of the java.util.concurrent classes above are unfamiliar to you, I highly recommend Java Concurrency in Practice by Brian Goetz (et al.). It's an excellent book.

Saturday, June 27, 2009

Embedded Groovy as an Application Extension Language

I recently worked with my client to add an extension mechanism (in this case, a very simple plug-in system) to their intranet Java web application.  It's initially meant for use by professional services staff and possibly other advanced users in the future.  Our first thought was to go with JavaScript via the Java Scripting API, since that pair of technologies was already in use elsewhere in the system for simple filtering expressions (e.g., "value > 10 && value < 100").  I wrote a few examples and discovered that the code quickly became a weird hybrid of Java and JavaScript that was very hard to read. ("Is that a Java String or a JavaScript String?…")  After a brief conversation with my client, we decided to instead go with Groovy for several reasons.  We can keep the code around as Strings for now, but easily compile it to class files later if our needs change.  Groovy's integration with Java is excellent and easy to understand.  If the user knows Java, but isn't comfortable with Groovy's many cool features, he or she can write normal Java (except for inner classes) and have it interpreted/compiled as Groovy.  What follows is a description of how I set it up.  Please let me know what you think of this approach, especially if you can suggest a way to improve it.

Each extension is a Groovy class extending a Java abstract adapter class that provides default implementations of all but one of the methods in a Java interface (ScriptingInterface).  The Java code used to load the extension gets a GroovyClassLoader using the following code:

GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader());

I use the following code to get the relevant class and instantiate it via its no-arg constructor, catching the (entertainingly-named) MultipleCompilationErrorsException along with several other exceptions:

String code = "<Groovy>"; 
Class<? extends ScriptingInterface> clazz = loader.parseClass(code); 
ScriptingInterface script = clazz.newInstance();

Does that sound like a reasonable way to do it?  It definitely works, but I'm not sure it's the best way.

Update: Ack!  For some reason, my Blogger settings changed from "New Posts Have Comments" to "New Posts Do Not Have Comments" through no action of my own!  While I try to figure out how to fix it (now that this post is no longer new), you can add any comments to this post's listing on DZone.

Update2: Problem fixed.  It turned out to be possible to turn on comments for a single post via the Blogger post editor.

Wednesday, May 27, 2009

FogBugzReporter: Introduction

This is the first post in what I plan to be a series about a small application named FogBugzReporter that I began writing in October of 2007.  I'd recently started using the on demand edition of FogBugz from Fog Creek Software to track my time spent consulting and was disappointed to discover that it had no direct way for me to generate time reports.  Fortunately, I discovered that along with the web UI, FogBugz also had a pseudo-REST API for interacting with the application (I say "pseudo-REST" because almost all operations can be performed with HTTP GETs, including ones that change state on the server).  I read the API docs, quickly wrote a simple Swing application in Java, and made it available to the rest of the FogBugz community.  Soon after, I started experimenting with Groovy and realized that porting the app would be a nice way to get some experience with the language, including SwingBuilder and the great APIs for processing XML.  I did that and eventually moved the code from a private Subversion repository to one on Google Code under an Apache license.  Until a few days ago, it sat for the most part unchanged.  In the meantime, my Groovy skills have improved a bit (I'm still no expert), the language has evolved, and the technologies around it have grown.  In this series, I plan to gradually bring the application up-to-date and polish up the code.  I'll update this posting with links to the other posts in the series as I write them.

Posts:

Planned Posts:

  • FogBugzReporter and Griffon
  • Suggestions?

Sunday, May 17, 2009

ConcurrentLinkedHashMap and Possible Alternatives

I mentioned in an earlier post that a project I'm working on needed a thread-safe class with behavior similar to LinkedHashMap, which maintains the order of entries while allowing sub-classes to set a (rather primitive) eviction policy.  I came upon and started using Ben Manes's ConcurrentLinkedHashMap, with only minor modifications to allow for easier sub-classing.  I've been pretty happy with it so far and have been meaning to take a look at recent changes that he and "zellster" have made since I last downloaded the code.

The same project is also using ehcache for caching.  I was looking forward to the release of version 1.6 and inquired about the expected release date on the developer's forum.  That kicked off an exchange between me and Greg Luck, the lead for ehcache, that eventually led to him mentioning some problems he'd encountered with ConcurrentLinkedHashMap.  I'm going to check in with Ben and let him respond to what Greg said, along with giving him a chance to provide a guess for when his new version of CLHM is likely to be usable.  I also need to look into what Greg was referring to in the changelog for ehcache 1.6 beta5 when he said, "Make MemoryStore eviction policies injectable."  Interesting…

Just to confuse matters, I was also recently looking over some materials discussing Infinispan, which will essentially be the 4.0 release of JBoss Cache, and saw this interesting blog entry on "Implementing a performant, thread-safe ordered data container".  In it, Manik Surtani mentions their newly implemented classes FIFODataContainer and LRUDataContainer, which sound like another plausible way to approach my problem.  I'll make sure to ask more about them in the comments for that post.

Saturday, May 16, 2009

JPC: x86 Emulator in Java

Last night, I was reading Caches and Maps in Terracotta by Alex Miller when I came upon his link to the JPC (a.k.a. JavaPC) Project.  It sounded familiar and I decided to follow the link.  It turns out to be an open source project implementing an impressively functional and performant x86 emulator in Java.  I had fun last night launching an MS-DOS environment within an applet (what a concept!) and playing Donkey Kong for the first time in ages.  According to the site, the emulated layer runs at about 20% of your processor's speed - not bad for a emulator written in pure Java.

Note: After my first visit to the site, it seemed to be having problems.  Just in case it had to do with visitor load, I changed the link above to point to the copy in Coral Cache.  The site is now totally back up and behaving normally.  If Coral has any problems or is slow, you can safely go to the site directly.

Update: I got an email from one of the JPC team members saying that they'll be at JavaOne this year with some new stuff.  I wish I could be there to see it.  I guess I'll have to wait for it to show up on their site.

Sunday, May 10, 2009

VisualVM and Cutting Method Calls by Over 1000x

I’ve been using VisualVM on and off with modest success since I first found out about it at JavaOne 2008.  In addition, since JDK 6 update 7, it’s been included as part of the standard JDK installation (released in July of 2008).  I was quite happy when it helped me identify bottlenecks and cut down the time to run a suite of unit tests by 50% (from 2 minutes to 1 minute).  After all, the less time it takes to run unit tests, the more often they’ll get run.  However, my biggest success using VisualVM came in early April, when I was asked to figure out why a use case was exhibiting disturbing performance characteristics.

When I first walked through the use case, it was taking about 10 seconds to run with 50 items.  The time appeared to be proportional to the number of items or perhaps even worse.  This was a scary prospect given that there would often be more than 10,000 items in a real production setting and that the use case was intended to be interactive (as opposed to a batch or background task).  A careful code review might have revealed the problem, but I knew it would be far more efficient to profile the code as a way to identify hot spots.  I started up VisualVM, connected to the relevant JVM, turned on CPU profiling, and collected data for the use case.  Sadly, I seem to have lost the relevant snapshot, so you’ll have to trust me when I tell you that the method SqlQueryFile.isSupported() was being called over 36 million times!  I made some minor tweaks to the method itself which improved its performance by about 10 percent – okay, but not nearly enough.  I next identified what was effectively a loop invariant.  The isSupported() method was being called repeatedly with the same query and schema.  As you can see from the snippets below, I pulled that check out of the nested loop.

Before:
for(Platform platform=p; platform != null; platform=platform.getParent()) {
  for(SqlQuery q : metricQueries) {
    if (isSupported(q, datasourceSchema)) {
      if(q.getMetricPath().equalsIgnoreCase(metricPath) &&
         q.getPlatform().equalsIgnoreCase(platform.getName())) {
        if(ret==null) {
          ret=q;
        } else {
          if(isMoreRecentThan(q, ret)) {
            ret=q;
          }
        }
      }
    }
  }
}
After:
Collection supportedQueries = new ArrayList();
for (SqlQuery q : metricQueries) {
  if (isSupported(q, datasourceSchema) && q.getMetricPath().equalsIgnoreCase(metricPath)) {
    supportedQueries.add(q);
  }
}

// need to optimized this code for better performance
for (Platform platform = p; platform != null; platform = platform.getParent()) {
  for (SqlQuery q : supportedQueries) {
    if (q.getPlatform().equalsIgnoreCase(platform.getName()) &&
        (ret == null || isMoreRecentThan(q, ret))) {
      ret = q;
    }
  }
}

When I ran the profiler again, it turned out I'd vastly reduced the number of calls to (~36 million to ~9 million) and the time spent in (80+% to 26.3%) the isSupported() method, as you can see in the picture below:

snapshot-040109-7pm

I probably could have left it there, but after taking another quick look, I noticed a very simple way to save even more time.  I could flip the order of the conditional expression in the first if statement.  That way, the cheap operation (which usually returns false) would come first and frequently allow us to skip the evaluation of isSupported().

if (q.getMetricPath().equalsIgnoreCase(metricPath) && isSupported(q, datasourceSchema)) {

To my surprise, this cut the number of calls to around 27,000 and the time spent in the method to 1%!

snapshot-040109-8pm

With these optimizations in place, the same use case with 11,000 items now took less than a second.  Thanks VisualVM!

Update: This post was a second place winner in the Java VisualVM Blogging Contest!

Sunday, May 3, 2009

Groovy versus Scala (Update)

Back in March of last year, I wrote a post comparing Groovy and Scala.  Enough time has passed that I thought it was worth revisiting the topic.

In my original post, I reached the conclusion that at least for me, it made sense to first focus on Groovy and then later learn more Scala.  I still feel that way, but my thoughts on the matter have evolved.  How about combining Groovy and Scala in the same program or architecture?  That thought had vaguely occurred to me already, but it was solidified by the discussion of Twitter’s use of Ruby and Scala.  They started off using Ruby (Ruby on Rails, in particular) to run their whole site.  When they ran into performance and scalability issues, they determined what was causing the most trouble (back-end tasks) and gradually converted the relevant parts of the system into Scala.  This kind of polyglot programming makes sense to me.  It follows the principle of “using the best tool for the job.”  I think the combination of Groovy and Scala makes even better sense: they’re designed to run and interoperate with other languages on the same VM.  Not surprisingly, I’m not the first person to think of this.  I found two posts from Andres Almiray (“Griffon: Groovy & Scala working together” and the follow up “Follow up on Griffon/Groovy/Scala”) showing some practical examples and another on a different blog discussing the ability jointly compile “Groovy+Scala+Java”.  I’m excited to watch and perhaps participate in these exciting developments.

Side Note: On the subject of Groovy, when my one-year IntelliJ license was close to expiring, I decided to check out NetBeans.  I was pleased to discover it had quite good Groovy and Grails support.  I’ve been using the 6.7 milestone builds and now the beta, in order to get support for Grails 1.1.  If you haven’t tried Groovy/Grails development in NetBeans yet, you should.

Update: Here are links to the items Andres mentioned in the comments

Update (Jan 12, 2010): Andres recently posted the highly relevant Groovy & Scala: a tale of two JVM languages

Sunday, April 5, 2009

Blogger Causing Problems for SyntaxHighlighter

I kept noticing blog entries with beautifully rendered source code snippets and finally clicked the blue question mark in the upper left of one and discovered that they were using Alex Gorbatchev's SyntaxHighlighter JavaScript library. For my last post, I followed the instructions in the Usage Guide, using the hosted version since I can't upload JS files to Blogger, at least as far as I know. If you look at my post, you'll notice that I have two 1 line Groovy snippets and one 5 line Java snippet. The 1 liners were no problem, but when I first tried to display the 5 lines of Java it showed up as just one line with visible <br> tags where the line breaks should have been. It turns out that when I pasted the code into Blogger's post editor, even though it was in HTML source mode, it inserted <br> tags for the line breaks even though they were showing up inside of a <pre> tag. It turns out that there are two solutions to the problem. I'll explain the better one first, although I didn't find out about it until trying the other one.

When I asked Google for help, it led me to a page talking about how to use SyntaxHighlighter with Blogger. The post itself didn't contain any new information for me, but the comments were useful. "Robje" had apparently experienced exactly the same problem as me. "Debiprasad" then asked, "What is your settings for 'Convert line breaks' set to? In my case, if I set it to 'Yes', it's inserting <br/> into codes defined under <pre> tag." Ah ha! I looked on the "Formatting" subtab under the "Settings" tab in the Blogger control panel and discovered that mine was set to "Yes". Ack! What an annoying default! With it set to "No", it seems to fix the problem.

In case that doesn't work for you, Google also brought me to a page on what must been the old home for SyntaxHighlighter. Once again, the gold was in the comments. "fahd.shariff" mentioned that if you use the post editor in Blogger in Draft, this isn't a problem. As I said earlier, I gave this a try before finding the preferable solution and it worked for me so it's a reasonable solution to fall back on.

Succinctly Groovy

I was reading a post on displaying Google Visualization charts in Grails on mrhaki's blog and noticed something interesting. In his code, mrhaki wanted to get a handle on the newest (most recently modified) file in a directory. His approach was to list the files in the directory, sort them (in ascending order), reverse that, and then get the zeroth item:
def xmlFile = dir.listFiles().sort{ file -> file.lastModified() }.reverse()[0]
It's a nice example of how you can express a somewhat complex flow in a single line of Groovy. Still, it seemed like overkill to me and another reader who failed to identify him or herself. That reader linked to the Groovy Collections page and suggested using a Comparator that sorted the list in descending order to start with, but didn't include a code snippet. I liked the fact that this approach avoids the extra work to reverse the sorted list, but I wasn't sure it would be possible to express it so compactly and it still seemed more complicated than necessary. I looked over the Collections page and was reminded of the min(Closure) and max(Closure) methods available on Groovy's enhanced collections. So, rather than sorting the list of files, you can just ask for the max as determined by last modified date:
def xmlFile = dir.listFiles().max{ it.lastModified() }
Nice and simple, eh? Ignoring the overhead of imports and class/method declaration, neither of which are necessary with the Groovy snippet, here's the most compact way I know of expressing this using the Java standard libraries:
File xmlFile = Collections.max(Arrays.asList(dir.listFiles()), new Comparator<File>() {
  public int compare(File file1, File file2) {
    return (int)(file1.lastModified() - file2.lastModified());
  }
});
I'm glad Groovy's out there!

Saturday, March 14, 2009

A Teeny Tiny Bit of Fame

When I noticed I was credited for a fix on the changelog page for Tomcat 5.5.27 (search for "Passell" on the page if you don't believe me!), it made me feel a bit giddy. Does that make me a total dork? Well, I've been using Tomcat since it emerged out of the Apache JServ project many years back, so it makes me proud to think that I've helped make it better, even if just a little bit.
 
Update: my fix was incorporated into Tomcat 6.0.20 as well.

Saturday, October 4, 2008

ConcurrentLinkedHashMap as In-Memory Cache

For my work, I was looking for a thread-safe equivalent of LinkedHashMap that would work well as the basis for an in-memory cache.  I was hoping that such a class might be showing up in the JSR166y project, but 'twas not to be.  After that, I tried googling for ConcurrentLinkedHashMap (my previous search had been for "concurrent LinkedHashMap" [minus the quotes]) and stumbled upon a small project at Google Code devoted to exactly what I was looking for: ConcurrentLinkedHashMap.  I've been looking over the code.  It seems pretty good and I might be helping out with it, but I'm not an expert with concurrency and the Java Memory Model to the extent really needed.  I'm in touch with the main author, who seems very amenable to suggestions and corrections.  We'll see how it works out.

Friday, May 9, 2008

Best Quote at JavaOne '08

"It's essentially impossible to avoid Swiss cheese." --Gil Tene, Azul Systems

Want to guess about the context? :)

Update: I think I've allowed enough time for everyone to guess. Jeff, with his more serious answer, was the closest. The quote came from the Q&A period that followed a Friday morning technical session, Performance Considerations in Concurrent Garbage-Collected Systems. Gil was explaining that whatever form of memory allocation you use, you'll eventually end up with memory fragmentation. In a JVM, if you use a garbage collector that's both parallel and concurrent, cleaning up that fragmentation can be done without a stop-the-world pause. Conveniently enough, the JVM that comes with Azul's boxes can be run in parallel/concurrent mode. :) Sorry that the quote is less funny when put in context.

Friday, February 8, 2008

Firebug and Ajax

Last night, I attended a NEJUG (New England Java Users Group) meeting which featured a talk titled "Designing for Ajax" given by Nathaniel T. "Nate" Schutta who has apparently spoken at several No Fluff Just Stuff conferences and co-authored the book Foundations of Ajax. It was an excellent talk, one of the best ones I've seen at a NEJUG meeting. He discussed a few Ajax JavaScript libraries/packages (Prototype, Scriptaculous, YUI, and Lightbox, for example) and coded several examples in front of the audience. He definitely made Ajaxifying what were previously flat web pages look quite simple. There were always caveats (to paraphrase, "In a production environment, you'd need to add a delay here so that you wouldn't get tool-tips popping up all over the place."), but the libraries seem to handle that mostly with sensible defaults. Although it wasn't directly related to Ajax, he also pointed out while doing the coding demos that he was using Firebug and YSlow for Firebug, very cool add-ons for Firefox that help you tune your web pages. Firebug includes a JavaScript debugger, powerful CSS helpers, and a bunch more. If you haven't used them before, you should check it out.

Wednesday, January 16, 2008

Experimenting with Scala

Although I'm really comfortable with Java and like it a lot, I came to the conclusion a while ago that I needed to add a language to my repertoire that facilitates rapid development. I know some JavaScript (which is actually a more powerful language than you might think), PHP, and Perl, but none of those quite fit the bill. I've been considering Python and Ruby for a while, but I've recently gotten very interested in Scala. I bought the e-book Programming in Scala available at Artima. I'll let you know what I think of it, along with posting a bunch of useful Scala-related links I've tracked down.

Friday, November 9, 2007

MyEclipse and reenabling Ctrl-Shift-T (Open Type)

I've been using Eclipse for a few years now and although I've always been a bit curious to try out NetBeans and IntelliJ IDEA, I've been pretty satisfied with it. I'm working with a client now who uses MyEclipse, a commercial package of plugins that runs on top of Eclipse, so I figured I'd give it a try. I installed MyEclipse 6 on top of Eclipse 3.3 (Callisto) and was pretty happy with it, until I tried typing Ctrl-Shift-T, Eclipse's handy shortcut for opening the VERY useful Open Type dialog, and it didn't work. Ack! I use that dialog dozens of times a day! I searched around on the Web to see if anyone else was having the same problem and it turned out several people had, but hadn't discovered a solution. Well, I just happened upon the fix. I'll post the steps here, but I'll also try to track down some of those posts of desperate people on forums and let them know about it.

For some hard to fathom reason, installing MyEclipse must deactivate the Open Type command for the Java Perspective. To re-enable it, making it work with Ctrl-Shift-T and appear in the Navigate menu, go to Window-->Customize Perspective..., choose the "Commands" tab and check the "Java Navigation" checkbox. Taa Daa!

Tuesday, September 25, 2007

Grove Hill Software is born

Well, this is my first post. Last week, I started my own software consulting company named Grove Hill Software, LLC. It’s been quite a bit of work to set things up, but I think it will be well worth it.

Here are some of the things I’ve done so far:

  • testing the waters to discover what work was out there and what it would pay
  • researching the cost of and how to obtain benefits, such as health, disability, and worker’s compensation insurance
  • the same for general and professional liability insurance
  • researching the options for the legal form of the business: sole proprietorship, S-corporation, LLC, and C-corporation
  • finding a lawyer and an accountant
  • deciding on a company name and actually forming the company
  • setting up a domain with email and webhosting
  • putting together a skeleton homepage
  • opening a company bank account

Here are some things I still need to do:

  • Investigate options for and set up a retirement account (SIMPLE, 401(k), SEP, etc.)
  • coming up with a logo (I have the advantage that my wife is a designer)
  • putting together a real homepage and overall website (the content will be the hard part)

I’ll come back and fill in more details as I go.

Sunday, September 23, 2007

About Me

I’ve been developing software in Java since 1997, and since 1998 professionally. On September 19, 2007, I started my own software consulting company named Grove Hill Software. I blogged about what that process was like. I shut down the business in 2015 (or maybe early 2016). I played Taiko (Japanese drumming) from December of 2005 until late 2009.