2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2020

04/21/2004: Catching Java Errors in the main() Method.

I’ve been using Java for more years than I care to mention but I never realized that you could catch errors as well as exceptions.i

So I’ve just added one more item to my toolbox. My main() method always uses this template:

try {
  // do something.
} catch (Error e) {
  e.printStackTrace();
} catch (Exception e) {
  e.printStrackTrace();
} finally {
  System.out.println("Done.");
}

Of course, in my real code I use log4j so that the errors are persisted.

04/08/2004: Optimization for JudoScript: JavaObject.pickMethod is an expensive call.

The getMethods() method of the Class class is an expensive call to make. So I added a static map to hold the method array between invokations of pickMethod().

This change reduced execution time of my test case by 3.4%. Instead of calling getMethods() 15,032 times it is only called once. And instead of creating 3.5 million objects only 386 objects are created. A nice bit of optimization if I do say so myself!

    private static final Map methodsInClass = new HashMap();

    final MatchFinder pickMethod(String methodName, Variable[] paramVals, int[] javaTypes) throws Exception {
        Class cls = null;
        for (int x = 0; x < this.classes.length; x++) {
            cls = this.classes[x];

            // make sure the map can't grow unbounded.
            if (methodsInClass.size() > 200) {
                methodsInClass.clear();
            }
            Method[] mthds = (Method[]) methodsInClass.get(cls);
            if (mthds == null) {
                mthds = cls.getMethods();
                methodsInClass.put(cls, mthds);
            }

            int len = (paramVals == null) ? 0 : paramVals.length;
            MatchFinder ret = new MatchFinder(0.0, len, javaTypes);
            for (int i = 0; i < mthds.length; i++) {
                if (mthds[i].getName().equals(methodName)) {
                    MatchFinder mf = matchParams(mthds[i].getParameterTypes(), paramVals, javaTypes);
                    if (mf.score > ret.score) {
                        ret = mf;
                        ret.method = mthds[i];
                    }
                }
            }
            if (ret.score > 0.0)
                return ret;
        }
        return NOT_MATCH;
    }