WKBReader: ParseException: Unknown WKB type x

I’m using the Java API JTS Topology Suite to do spatial operations. To convert a byte array into a Geometry object the following helper class was used:

public class JTSHelper {
	static WKBReader wkbReader = new WKBReader();

	public static Geometry bytesToGeometry(byte geometryBytes[]) throws ParseException {
		return wkbReader.read(geometryBytes);
	}
}

This seemed to work well, but in the logfile we saw intermittent failures caused by this class:
ParseException: Unknown WKB type 139
ParseException: Unknown WKB type 0
ParseException: Unknown WKB type 17

The WKB type numbers were always different, but when checking the incoming byte arrays everything seems to be OK.

With apache benchmark tool the failures could be reproduced when increasing the number of concurrent requests:
ab -n 1000 -c 10 http://localhost:8080/project/test-action

A look at JavaDoc of WKBReader shows that this class is not thread-safe. Therefore the solution is to put WKBReader in ThreadLocal:

public class JTSHelper {
	static ThreadLocal<WKBReader> wkbReader	= new ThreadLocal<WKBReader>() {
		protected WKBReader initialValue() { return new WKBReader(); };
	};

	public static Geometry bytesToGeometry(byte geometryBytes[]) throws ParseException {
		WKBReader reader = wkbReader.get();
		return reader.read(geometryBytes);
	}
}

Versions: JTS 1.8, JDK 5

Advertisements
Posted in Java. Tags: , , . Leave a Comment »