From fe7f573deb18adfb0bbb143a5d25225ca8aaff3d Mon Sep 17 00:00:00 2001 From: Mike Barry Date: Tue, 27 Jul 2021 08:38:43 -0400 Subject: [PATCH] synchronize inserts --- .../onthegomap/flatmap/geo/PointIndex.java | 5 ++++- .../onthegomap/flatmap/geo/PolygonIndex.java | 20 ++++++++++++++++++- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/core/src/main/java/com/onthegomap/flatmap/geo/PointIndex.java b/core/src/main/java/com/onthegomap/flatmap/geo/PointIndex.java index b0aa5292..76ea6a32 100644 --- a/core/src/main/java/com/onthegomap/flatmap/geo/PointIndex.java +++ b/core/src/main/java/com/onthegomap/flatmap/geo/PointIndex.java @@ -79,7 +79,10 @@ public class PointIndex { public void put(Geometry geom, T item) { if (geom instanceof Point point && !point.isEmpty()) { Envelope envelope = Objects.requireNonNull(point.getEnvelopeInternal()); - index.insert(envelope, new GeomWithData<>(point.getCoordinate(), item)); + // need to externally synchronize inserts into the STRTree + synchronized (this) { + index.insert(envelope, new GeomWithData<>(point.getCoordinate(), item)); + } } else if (geom instanceof GeometryCollection geoms) { for (int i = 0; i < geoms.getNumGeometries(); i++) { put(geoms.getGeometryN(i), item); diff --git a/core/src/main/java/com/onthegomap/flatmap/geo/PolygonIndex.java b/core/src/main/java/com/onthegomap/flatmap/geo/PolygonIndex.java index 0c1f4b56..fdd78cc7 100644 --- a/core/src/main/java/com/onthegomap/flatmap/geo/PolygonIndex.java +++ b/core/src/main/java/com/onthegomap/flatmap/geo/PolygonIndex.java @@ -22,7 +22,21 @@ public class PolygonIndex { return new PolygonIndex<>(); } + private volatile boolean built = false; + + private void build() { + if (!built) { + synchronized (this) { + if (!built) { + index.build(); + built = true; + } + } + } + } + public List getContaining(Point point) { + build(); List items = index.query(point.getEnvelopeInternal()); return getContaining(point, items); } @@ -45,6 +59,7 @@ public class PolygonIndex { } public List getContainingOrNearest(Point point) { + build(); List items = index.query(point.getEnvelopeInternal()); // optimization: if there's only one then skip checking contains/distance if (items.size() == 1) { @@ -81,7 +96,10 @@ public class PolygonIndex { public synchronized void put(Geometry geom, T item) { if (geom instanceof Polygon poly) { - index.insert(poly.getEnvelopeInternal(), new GeomWithData<>(poly, item)); + // need to externally synchronize inserts into the STRTree + synchronized (this) { + index.insert(poly.getEnvelopeInternal(), new GeomWithData<>(poly, item)); + } } else if (geom instanceof GeometryCollection geoms) { for (int i = 0; i < geoms.getNumGeometries(); i++) { put(geoms.getGeometryN(i), item);