How to get the running tasks for a Java Executor…

I just had the issue of debugging a large concurrent job that ran using Java’s Executor and ExecutorService classes for concurrency.

The job comprised of roughly 50,000 tasks submitted recursively over a multi-GB data set that took 5hrs to process. The bug left a single task in the queue hanging indefinitely, thus the job never completing. There’s no way to kill a Thread in Java, and if you have blocking I/O it can be difficult to implement interrupt() such that it works correctly.

This is the point I found it’s quite difficult to actually expose at run-time what the hell Java’s Executor is actually doing at any point in time.

The successful choice I found was to create a custom ThreadPoolExecutor which trapped the creation of a FutureTask and the start/stop of any given task. I expect these hooks are there for this purpose, but it sure isn’t obvious how to do this.

It seems odd that the API doesn’t include any way to gather info about what’s happening inside the Executor, and also, there’s not even a toString() implementation for wrapping classes like FutureTask which would bubble your Runnable or Callable classes’ toString() methods.

Oh well!

Here’s an example:

private static final int NUM_THREADS = 4;
private final Logger log = Logger.getLogger(getClass());

private LinkedBlockingQueue< Runnable> taskQueue = new LinkedBlockingQueue< Runnable>();
private List< Runnable> running = Collections.synchronizedList(new ArrayList());

public void doSomeStuffConcurrently() {
	Executor executor =
		new ThreadPoolExecutor(NUM_THREADS, NUM_THREADS,
			0L, TimeUnit.MILLISECONDS,
			taskQueue,
			Executors.defaultThreadFactory())
	{

		@Override
		protected < T> RunnableFuture< T> newTaskFor(final Runnable runnable, T value) {
			return new FutureTask< T>(runnable, value) {
				@Override
				public String toString() {
					return runnable.toString();
				}
			};
		}

		@Override
		protected void beforeExecute(Thread t, Runnable r) {
			super.beforeExecute(t, r);
			running.add(r);
		}

		@Override
		protected void afterExecute(Runnable r, Throwable t) {
			super.afterExecute(r, t);
			running.remove(r);
			log.info("RUNNING: " + running);
		}
	};

	executor.execute(new Runnable() {

		@Override
		public void run() {
			// so some stuff
		}

		@Override
		public String toString() {
			return "describe the task here!";
		}
	});
}
Posted in Java, Software Engineering | Tagged Java, tips | Leave a comment

Writing reflective unit tests to improve code quality

I’ve found that writing JUnit tests that do classpath scanning combined with reflection is a way to write unit tests that cross-cut the entire application. This can be useful to prevent anti-patterns, enforce code standards or just to prevent common dumb errors.

It also notable that tests like this will not just cover code that exists today, but code that get’s written in the future too.

Generally these tests won’t actually execute classes found the class path, but instead reflect on class structure, annotations or method IO. But you could also conceivably write tests that instantiated classes and tested behavior too.

Here’s an example of a classpath scanning, reflective test case.

Background: I’ve used warp-persist in the past to do JPA transactions with Guice projects. This gives you a @Transactional annotation which will apply a transaction across the method, unless exception(s) of specified types are thrown. Unfortunately, the warp-persist library has a design flaw, in that the default is that checked exceptions ROLLBACK, but runtime (non-checked) exceptions DO NOT. Why you’d want this is unclear to me, so we always end up writing {Exception.class, RuntimeException.class} to cover all cases – something that is easy to forget to do!

The test below, find’s all uses of the @Transactional annotation and verifies that each use of the annotation lists both RuntimeException.class and Exception.class as the rollback conditions.

By scanning the classpath, any new (or old) code will be flagged if the developer forgets this bit of housekeeping (this test has saved my bacon more than once).

package com.mycom;

import com.visural.common.ClassFinder;
import com.wideplay.warp.persist.Defaults.DefaultUnit;
import com.wideplay.warp.persist.Transactional;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import junit.framework.TestCase;

public class TransactionalTest extends TestCase {

    public void testTransactionalDoesntCreateBadBugs() throws ClassNotFoundException, Exception {
        ClassFinder cf = new ClassFinder("com.mycom", true);
        List < String >  invalid = new ArrayList < String > ();
        Set < Class >  classes = cf.find();
        for (Class c : classes) {
            for (Method m : c.getDeclaredMethods()) {
                if (m.getAnnotation(Transactional.class) != null) {
                    List < Class < ? extends Exception >  >  ex = Arrays.asList(m.getAnnotation(Transactional.class).rollbackOn());
                    if (!ex.contains(Exception.class) || !ex.contains(RuntimeException.class)) {
                        invalid.add(c.getName()+"#"+m.getName()+"\n");
                    }
                }
            }
        }
        if (!invalid.isEmpty()) {
            Collections.sort(invalid);
            throw new Exception("The following methods use @Transactional, but do not rollback on Exception & RuntimeException: "+invalid.toString());
        }
    }
}

This is a slightly contrived example, in the sense that it is working around a design flaw in a 3rd party library. But, this technique is useful in many cases where you have design patterns, standards or anti-patterns which you want to enforce or prevent.

Here’s a few examples:

  • Enforce all model classes should be Serializable
  • Enforce class or method naming conventions
  • Enforce specific package structures / hierarchies
  • Ensure that arguments/returns are not overly specific e.g. return List not ArrayList

The tests can be as broad or narrow as your design rules. I’m not suggesting that the above examples are good ideas in all cases. But writing tests like these is a way to formalise a team/project standard in a more useful way, than writing it down in a document or wiki.

There be exceptions to many of the rules or patterns being tested, but you can always write the exceptions into the test.

Overall the advantages of this approach are:

  • An opportunity to express the design pattern in the actual product code base as an executable test.
  • A way to ensure that a new developer is made aware of the design pattern, at the time it is most relevant: when they need to apply it.
  • A place to document the exceptions to the pattern, and why they are allowable.
  • A way to keep everyone honest. Even experienced developers take short cuts, or are forgetful sometimes.

It’s a win all round. Not all Java developers are comfortable with class-path scanning and reflection/introspection (maybe they should be), but not all developers will need to write these tests, as they are probably best handled by a technical lead.

Footnote: if you want a general-purpose utility for doing class path scanning, then my library visural-common has ClassFinder.java – a way to search the class path for specific classes (as illustrated above).

Posted in Java, Software Engineering | Tagged Java, junit, tips, visural-common, warp-persist | 3 Comments

Quick Tip – Make Anything A Windows Service

I recently had to get nginx running as a Windows service and I came across a little project called “winsw” (Windows Service Wrapper) which was created by Kohsuke Kawaguchi – creator of Hudson/Jenkins.

Apparently he created it while at Sun for Hudson. The other popular Java Service Wrapper for Windows (by Tanuki) is GPL licenced and has commercial licences available. Kohsuke created “winsw” so there was an option for Hudson available under a more permissive licence than GPL.

Conveniently, “winsw” can actually be used with pretty much any process you want to turn into a windows service, not just Java apps.

It’s got really simple configuration with an XML file e.g.

<service>
  <id>fisheye</id>
  <name>dev.net FishEye</name>
  <description>FishEye</description>
  <executable>%FISHEYE_HOME%\bin\fisheyectl.bat</executable>
  <logpath>P:\dev\logs\os\windows\services</logpath>
  <logmode>roll</logmode>
  <depend>Spooler</depend>
  <startargument>run</startargument>
  <stopargument>stop</stopargument>
</service>

And it’s basically just a single EXE file (31KB) and the XML config (although it does require .NET 3).

Anyhow, this is a nice little tool to have in your toolbelt, particularly for getting non-Windows friendly stuff running on Windows servers!

Posted in IT, Software Engineering | Tagged open-source, servers, tips, windows | Leave a comment

visural-wicket 0.7.0 release with support for Wicket 1.5

Today I pushed out release 0.7.0 of visural-wicket. This release is primarily a bug-fix and minor enhancement release, with one major feature – support for Wicket 1.5 which was released as stable yesterday!

You can get the downloads here (note there is a separate package for Wicket 1.4 and Wicket 1.5) -

Using Maven? Use this set up guide instead.

The full list of changes is here. Mostly these are bug fixes. Both the Wicket 1.4 and Wicket 1.5 versions incorporate the fixes.

The Wicket 1.5 library has not had extensive testing as yet, so please lodge any issues found on the project issue tracker, or at the Google Group.

Please note also, that the source for the project migrated to GitHub not long ago. If you’d like to contribute then I would welcome pull requests or patches!

Hope to get through some more of the issues lodged in the project tracker soon. I’m slowing adjusting to being a Dad, and still having time to work on my projects such as this :)

Posted in Java, Software Engineering, Wicket | Tagged Java, open-source, visural-common, visural-wicket, wicket | 2 Comments