locationtech / jts

The JTS Topology Suite is a Java library for creating and manipulating vector geometry.
Other
1.96k stars 440 forks source link

Concurrency problem in PackedCoordinateSequence cache population #187

Open dr-jts opened 7 years ago

dr-jts commented 7 years ago

There is a race condition in the PackedCoordinateSequence.getCachedCoords method. It is possible for the coordRef field to be nulled out after it has passed the null check, resulting in a NPE when coordRef.get() is called.

See https://github.com/NetTopologySuite/NetTopologySuite/pull/193 for details.

jandam commented 6 years ago

The fix is simple. Introduce local variable to getCachedCoords

private Coordinate[] getCachedCoords() {
    Reference<Coordinate[]> coordRef = this.coordRef;  // added this line - local variable from field
    if (coordRef != null) {
      return coordRef.get();
      if (coords != null) {
        return coords;
      } else {
        // System.out.print("-");
        this.coordRef = null;  // added 'this.' - null out field
        return null;
      }
    } else {
      // System.out.print("-");
      return null;
    }

  }

) I don't think that it is necessary to reset coordRef to null in this method when value is cleared. ) Field coordRef can be made volatile to better concurrency. *) Field coordRef can use be declared as Reference<..> instead of more specific SoftReference<...>