You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sis.apache.org by de...@apache.org on 2021/07/10 19:14:41 UTC

[sis] branch geoapi-4.0 updated (e33d72e -> ced335d)

This is an automated email from the ASF dual-hosted git repository.

desruisseaux pushed a change to branch geoapi-4.0
in repository https://gitbox.apache.org/repos/asf/sis.git.


    from e33d72e  Make `ResampledGridCoverage` more robust to case where the `sliceExtent` has more than 2 dimensions, and the extra-dimensions may get a size greater than 1 after conversion to source grid coordinates. Also add a margin for interpolations.
     new 1b26a1a  Try to reduce a problem of weak references cleaned too early, which caused the EPSG factory to recreate the same objects again and again. Factory is still creating more objects than we would expect during "search" operations, but the situation with this fix is a bit better.
     new ced335d  Compute `PlanarImage.GRID_GEOMETRY_KEY` property for image read from GeoTIFF files.

The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../org/apache/sis/gui/coverage/GridTileCache.java |   3 +-
 .../org/apache/sis/coverage/grid/GridExtent.java   |   8 +-
 .../org/apache/sis/coverage/grid/GridGeometry.java |  39 ++++++
 .../internal/coverage/j2d/DeferredProperty.java    |  56 ++++++++
 .../apache/sis/coverage/grid/GridGeometryTest.java |  23 ++++
 .../factory/ConcurrentAuthorityFactory.java        |  58 ++++++--
 .../factory/IdentifiedObjectFinder.java            |   4 +-
 .../sis/referencing/factory/ReferenceKeeper.java   | 151 +++++++++++++++++++++
 .../operation/CoordinateOperationFinder.java       |  10 +-
 .../operation/CoordinateOperationRegistry.java     |  11 +-
 .../sis/internal/util/StandardDateFormat.java      |   4 +-
 .../java/org/apache/sis/util/collection/Cache.java |  12 +-
 .../sis/internal/storage/TiledGridCoverage.java    |  14 +-
 13 files changed, 360 insertions(+), 33 deletions(-)
 create mode 100644 core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/ReferenceKeeper.java

[sis] 02/02: Compute `PlanarImage.GRID_GEOMETRY_KEY` property for image read from GeoTIFF files.

Posted by de...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

desruisseaux pushed a commit to branch geoapi-4.0
in repository https://gitbox.apache.org/repos/asf/sis.git

commit ced335d1cede92c19a81b52d18f8aee6ce5226a5
Author: Martin Desruisseaux <ma...@geomatys.com>
AuthorDate: Sat Jul 10 17:01:00 2021 +0200

    Compute `PlanarImage.GRID_GEOMETRY_KEY` property for image read from GeoTIFF files.
---
 .../org/apache/sis/coverage/grid/GridExtent.java   |  8 ++--
 .../org/apache/sis/coverage/grid/GridGeometry.java | 39 +++++++++++++++
 .../internal/coverage/j2d/DeferredProperty.java    | 56 ++++++++++++++++++++++
 .../apache/sis/coverage/grid/GridGeometryTest.java | 23 +++++++++
 .../sis/internal/storage/TiledGridCoverage.java    | 14 ++++--
 5 files changed, 131 insertions(+), 9 deletions(-)

diff --git a/core/sis-feature/src/main/java/org/apache/sis/coverage/grid/GridExtent.java b/core/sis-feature/src/main/java/org/apache/sis/coverage/grid/GridExtent.java
index fdef600..82bdb09 100644
--- a/core/sis-feature/src/main/java/org/apache/sis/coverage/grid/GridExtent.java
+++ b/core/sis-feature/src/main/java/org/apache/sis/coverage/grid/GridExtent.java
@@ -1436,9 +1436,6 @@ public class GridExtent implements GridEnvelope, LenientComparable, Serializable
      * Returns an extent translated by the given amount of cells compared to this extent.
      * The returned extent has the same {@linkplain #getSize(int) size} than this extent,
      * i.e. both low and high grid coordinates are displaced by the same amount of cells.
-     * The given translation vector should have a length equal to this extent
-     * {@linkplain #getDimension() dimension}, but shorter arrays are allowed:
-     * missing values are assumed zero (i.e. the extent is not translated in missing dimensions).
      *
      * <div class="note"><b>Example:</b>
      * for an extent (x: [0…10], y: [2…4], z: [0…1]) and a translation {-2, 2},
@@ -1449,12 +1446,13 @@ public class GridExtent implements GridEnvelope, LenientComparable, Serializable
      * If the array is shorter, missing values default to 0 (i.e. no translation in unspecified dimensions).
      * If the array is longer, extraneous values are ignored.
      *
-     * @param  translation  translation to apply on each axis in order, or {@code null} if none.
-     * @return a grid-extent whose coordinates (both low and high ones) have been translated by given amounts.
+     * @param  translation  translation to apply on each axis in order.
+     * @return a grid extent whose coordinates (both low and high ones) have been translated by given amounts.
      *         If the given translation is a no-op (no value or only 0 ones), then this extent is returned as is.
      * @throws ArithmeticException if the translation results in coordinates that overflow 64-bits integer.
      *
      * @see #startsAtZero()
+     * @see GridGeometry#translate(long...)
      *
      * @since 1.1
      */
diff --git a/core/sis-feature/src/main/java/org/apache/sis/coverage/grid/GridGeometry.java b/core/sis-feature/src/main/java/org/apache/sis/coverage/grid/GridGeometry.java
index 9b50485..b477e72 100644
--- a/core/sis-feature/src/main/java/org/apache/sis/coverage/grid/GridGeometry.java
+++ b/core/sis-feature/src/main/java/org/apache/sis/coverage/grid/GridGeometry.java
@@ -1285,6 +1285,45 @@ public class GridGeometry implements LenientComparable, Serializable {
     }
 
     /**
+     * Returns a grid geometry translated by the given amount of cells compared to this grid.
+     * The returned grid has the same {@linkplain GridExtent#getSize(int) size} than this grid,
+     * i.e. both low and high grid coordinates are displaced by the same amount of cells.
+     * The "grid to CRS" transforms are adjusted accordingly in order to map to the same
+     * "real world" coordinates.
+     *
+     * <h4>Number of arguments</h4>
+     * The {@code translation} array length should be equal to the {@linkplain #getDimension() number of dimensions}.
+     * If the array is shorter, missing values default to 0 (i.e. no translation in unspecified dimensions).
+     * If the array is longer, extraneous values are ignored.
+     *
+     * @param  translation  translation to apply on each grid axis in order.
+     * @return a grid geometry whose coordinates (both low and high ones) and
+     *         the "grid to CRS" transforms have been translated by given amounts.
+     *         If the given translation is a no-op (no value or only 0 ones), then this grid is returned as is.
+     * @throws ArithmeticException if the translation results in coordinates that overflow 64-bits integer.
+     *
+     * @see GridExtent#translate(long...)
+     *
+     * @since 1.1
+     */
+    public GridGeometry translate(final long... translation) {
+        ArgumentChecks.ensureNonNull("translation", translation);
+        final double[] vector = new double[getDimension()];
+        boolean isZero = true;
+        for (int i=Math.min(vector.length, translation.length); --i >= 0;) {
+            isZero &= (translation[i] == 0);
+            vector[i] = Math.negateExact(translation[i]);
+        }
+        if (isZero) {
+            return this;
+        } else try {
+            return new GridGeometry(this, extent.translate(translation), MathTransforms.translation(vector));
+        } catch (TransformException e) {
+            throw new AssertionError(e);
+        }
+    }
+
+    /**
      * Returns a grid geometry that encompass only some dimensions of this grid geometry.
      * The specified dimensions will be copied into a new grid geometry if necessary.
      * The selection is applied on {@linkplain #getExtent() grid extent} dimensions;
diff --git a/core/sis-feature/src/main/java/org/apache/sis/internal/coverage/j2d/DeferredProperty.java b/core/sis-feature/src/main/java/org/apache/sis/internal/coverage/j2d/DeferredProperty.java
index 2473e4e..498b0a9 100644
--- a/core/sis-feature/src/main/java/org/apache/sis/internal/coverage/j2d/DeferredProperty.java
+++ b/core/sis-feature/src/main/java/org/apache/sis/internal/coverage/j2d/DeferredProperty.java
@@ -16,8 +16,13 @@
  */
 package org.apache.sis.internal.coverage.j2d;
 
+import java.util.Map;
+import java.util.Collections;
 import java.util.function.Function;
 import java.awt.image.RenderedImage;
+import org.apache.sis.image.PlanarImage;
+import org.apache.sis.coverage.grid.GridExtent;
+import org.apache.sis.coverage.grid.GridGeometry;
 
 
 /**
@@ -70,4 +75,55 @@ public final class DeferredProperty {
         }
         return value;
     }
+
+    /**
+     * Creates a deferred property for computing the value of {@link PlanarImage#GRID_GEOMETRY_KEY}.
+     *
+     * @param  grid        the grid geometry of the grid coverage rendered as an image.
+     * @param  dimensions  the dimensions to keep from the coverage grid geometry.
+     * @return a deferred property for computing the grid geometry of an image.
+     */
+    public static Map<String,Object> forGridGeometry(final GridGeometry grid, final int[] dimensions) {
+        return Collections.singletonMap(PlanarImage.GRID_GEOMETRY_KEY,
+                new DeferredProperty(new ImageGeometry(grid, dimensions)));
+    }
+
+    /**
+     * A deferred property for computing the value of {@link PlanarImage#GRID_GEOMETRY_KEY}.
+     */
+    private static final class ImageGeometry implements Function<RenderedImage, GridGeometry> {
+        /** The grid geometry of the grid coverage rendered as an image. */
+        private final GridGeometry grid;
+
+        /** The dimensions to keep from the coverage grid geometry. */
+        private final int dimX, dimY;
+
+        /**
+         * Creates a deferred property for an image grid geometry.
+         *
+         * @param grid        the grid geometry of the grid coverage rendered as an image.
+         * @param dimensions  the dimensions to keep from the coverage grid geometry.
+         */
+        public ImageGeometry(final GridGeometry grid, final int[] dimensions) {
+            this.grid = grid;
+            this.dimX = dimensions[0];
+            this.dimY = dimensions[1];
+        }
+
+        /**
+         * Invoked when the {@link PlanarImage#GRID_GEOMETRY_KEY} value needs to be computed.
+         * The image should have been rendered from a grid coverage having the grid geometry
+         * given at construction time.
+         *
+         * @param  image  the image for which to compute the property.
+         * @return the grid geometry property computed for the given image.
+         */
+        @Override
+        public GridGeometry apply(final RenderedImage image) {
+            final GridExtent extent = grid.getExtent();
+            return grid.reduce(dimX, dimY).translate(
+                    Math.subtractExact(image.getMinX(), extent.getLow(dimX)),
+                    Math.subtractExact(image.getMinY(), extent.getLow(dimY)));
+        }
+    }
 }
diff --git a/core/sis-feature/src/test/java/org/apache/sis/coverage/grid/GridGeometryTest.java b/core/sis-feature/src/test/java/org/apache/sis/coverage/grid/GridGeometryTest.java
index b3c4f2b..87d71e2 100644
--- a/core/sis-feature/src/test/java/org/apache/sis/coverage/grid/GridGeometryTest.java
+++ b/core/sis-feature/src/test/java/org/apache/sis/coverage/grid/GridGeometryTest.java
@@ -16,6 +16,7 @@
  */
 package org.apache.sis.coverage.grid;
 
+import org.opengis.geometry.Envelope;
 import org.opengis.metadata.spatial.DimensionNameType;
 import org.opengis.referencing.datum.PixelInCell;
 import org.opengis.referencing.operation.Matrix;
@@ -432,6 +433,28 @@ public final strictfp class GridGeometryTest extends TestCase {
     }
 
     /**
+     * Tests {@link GridGeometry#translate(long...)}.
+     */
+    @Test
+    public void testTranslate() {
+        GridGeometry grid = new GridGeometry(
+                new GridExtent(17, 10),
+                PixelInCell.CELL_CENTER,
+                MathTransforms.linear(new Matrix3(
+                    1,   0,  -7,
+                    0,  -1,  50,
+                    0,   0,   1)),
+                HardCodedCRS.WGS84);
+        /*
+         * The "real world" envelope should be unchanged by grid translation.
+         */
+        final Envelope envelope = grid.getEnvelope();
+        grid = grid.translate(12, 15);
+        assertExtentEquals(new long[] {12, 15}, new long[] {12 + 16, 15 + 9}, grid.getExtent());
+        assertEquals(envelope, grid.getEnvelope());
+    }
+
+    /**
      * Tests {@link GridGeometry#reduce(int...)}.
      */
     @Test
diff --git a/storage/sis-storage/src/main/java/org/apache/sis/internal/storage/TiledGridCoverage.java b/storage/sis-storage/src/main/java/org/apache/sis/internal/storage/TiledGridCoverage.java
index af68b33..99e5962 100644
--- a/storage/sis-storage/src/main/java/org/apache/sis/internal/storage/TiledGridCoverage.java
+++ b/storage/sis-storage/src/main/java/org/apache/sis/internal/storage/TiledGridCoverage.java
@@ -28,6 +28,7 @@ import org.opengis.geometry.MismatchedDimensionException;
 import org.apache.sis.coverage.grid.GridCoverage;
 import org.apache.sis.coverage.grid.GridExtent;
 import org.apache.sis.coverage.grid.DisjointExtentException;
+import org.apache.sis.internal.coverage.j2d.DeferredProperty;
 import org.apache.sis.internal.coverage.j2d.TiledImage;
 import org.apache.sis.storage.DataStoreException;
 import org.apache.sis.util.resources.Errors;
@@ -294,8 +295,8 @@ public abstract class TiledGridCoverage extends GridCoverage {
                         Errors.Keys.MismatchedDimension_3, "sliceExtent", dimension, sd));
             }
         }
-        final int[] sd = sliceExtent.getSubspaceDimensions(BIDIMENSIONAL);
-        if (sd[1] != 1) {
+        final int[] selectedDimensions = sliceExtent.getSubspaceDimensions(BIDIMENSIONAL);
+        if (selectedDimensions[1] != 1) {
             // TODO
             throw new UnsupportedOperationException("Non-horizontal slices not yet implemented.");
         }
@@ -321,7 +322,7 @@ public abstract class TiledGridCoverage extends GridCoverage {
                         throw new DisjointExtentException(message);
                     }
                 }
-                final long lower =                Math.max(toSubsampledPixel(               multiplyExact(tileLo, tileSize[i]),  i), min);
+                final long lower = /* inclusive */Math.max(toSubsampledPixel(/* inclusive */multiplyExact(tileLo, tileSize[i]),  i), min);
                 final long upper = incrementExact(Math.min(toSubsampledPixel(decrementExact(multiplyExact(tileUp, tileSize[i])), i), max));
                 imageSize[i] = toIntExact(subtractExact(upper, lower));
                 offsetAOI[i] = toIntExact(subtractExact(lower, aoiMin));
@@ -332,7 +333,12 @@ public abstract class TiledGridCoverage extends GridCoverage {
              * Get all tiles in the specified region. I/O operations, if needed, happen here.
              */
             final WritableRaster[] result = readTiles(new AOI(tileLower, tileUpper, offsetAOI, dimension));
-            image = new TiledImage(null, colors, imageSize[0], imageSize[1], tileLower[0], tileLower[1], result);
+            /*
+             * Wraps in an image all the tiles that we just read, together with the following properties:
+             *    - Two-dimensional conversion from pixel coordinates to "real world" coordinates.
+             */
+            final Map<String,Object> properties = DeferredProperty.forGridGeometry(getGridGeometry(), selectedDimensions);
+            image = new TiledImage(properties, colors, imageSize[0], imageSize[1], tileLower[0], tileLower[1], result);
         } catch (Exception e) {     // Too many exception types for listing them all.
             throw new CannotEvaluateException(Resources.forLocale(getLocale()).getString(
                     Resources.Keys.CanNotRenderImage_1, getDisplayName()), e);

[sis] 01/02: Try to reduce a problem of weak references cleaned too early, which caused the EPSG factory to recreate the same objects again and again. Factory is still creating more objects than we would expect during "search" operations, but the situation with this fix is a bit better.

Posted by de...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

desruisseaux pushed a commit to branch geoapi-4.0
in repository https://gitbox.apache.org/repos/asf/sis.git

commit 1b26a1a5ff26739c75b3cbf7a96dda88826116b9
Author: Martin Desruisseaux <ma...@geomatys.com>
AuthorDate: Sat Jul 10 12:06:16 2021 +0200

    Try to reduce a problem of weak references cleaned too early, which caused the EPSG factory to recreate the same objects again and again.
    Factory is still creating more objects than we would expect during "search" operations, but the situation with this fix is a bit better.
---
 .../org/apache/sis/gui/coverage/GridTileCache.java |   3 +-
 .../factory/ConcurrentAuthorityFactory.java        |  58 ++++++--
 .../factory/IdentifiedObjectFinder.java            |   4 +-
 .../sis/referencing/factory/ReferenceKeeper.java   | 151 +++++++++++++++++++++
 .../operation/CoordinateOperationFinder.java       |  10 +-
 .../operation/CoordinateOperationRegistry.java     |  11 +-
 .../sis/internal/util/StandardDateFormat.java      |   4 +-
 .../java/org/apache/sis/util/collection/Cache.java |  12 +-
 8 files changed, 229 insertions(+), 24 deletions(-)

diff --git a/application/sis-javafx/src/main/java/org/apache/sis/gui/coverage/GridTileCache.java b/application/sis-javafx/src/main/java/org/apache/sis/gui/coverage/GridTileCache.java
index 1afccc4..444c3ea 100644
--- a/application/sis-javafx/src/main/java/org/apache/sis/gui/coverage/GridTileCache.java
+++ b/application/sis-javafx/src/main/java/org/apache/sis/gui/coverage/GridTileCache.java
@@ -36,10 +36,11 @@ final class GridTileCache extends LinkedHashMap<GridTile,GridTile> {
      * Creates a new cache of tiles.
      */
     GridTileCache() {
+        super(16, 0.75f, true);
     }
 
     /**
-     * Clears the latest tile if this map has reached its maximal capacity.
+     * Clears the eldest tile if this map has reached its maximal capacity.
      * In the common case where there is no error, the whole entry will be discarded.
      *
      * @param  entry  the eldest entry.
diff --git a/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/ConcurrentAuthorityFactory.java b/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/ConcurrentAuthorityFactory.java
index 213160c..f1892ed 100644
--- a/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/ConcurrentAuthorityFactory.java
+++ b/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/ConcurrentAuthorityFactory.java
@@ -95,7 +95,7 @@ import org.apache.sis.util.resources.Messages;
  * Subclasses should select the interfaces that they choose to implement.
  *
  * @author  Martin Desruisseaux (IRD, Geomatys)
- * @version 0.8
+ * @version 1.1
  *
  * @param <DAO>  the type of factory used as Data Access Object (DAO).
  *
@@ -132,7 +132,9 @@ public abstract class ConcurrentAuthorityFactory<DAO extends GeodeticAuthorityFa
     private final Map<Class<?>,Boolean> inherited = new IdentityHashMap<>();
 
     /**
-     * The pool of cached objects.
+     * The pool of cached objects. Keys are (type, code) tuples; the type is stored because the same code
+     * may be used for different kinds of objects. Values are usually instances of {@link IdentifiedObject},
+     * but can also be instances of unrelated types such as {@link Extent}.
      */
     private final Cache<Key,Object> cache;
 
@@ -140,11 +142,24 @@ public abstract class ConcurrentAuthorityFactory<DAO extends GeodeticAuthorityFa
      * The pool of objects identified by {@link Finder#find(IdentifiedObject)}.
      * Values may be an empty set if an object has been searched but has not been found.
      *
+     * <p>Keys are typically "foreigner" objects (not objects retained in the {@linkplain #cache}),
+     * otherwise we would not need to search for their authority code. Because keys are retained by
+     * weak references, some strong references to the identified objects should be kept outside.
+     * This is the purpose of {@link #findPoolLatestQueries}.</p>
+     *
      * <p>Every access to this pool must be synchronized on {@code findPool}.</p>
      */
     private final Map<IdentifiedObject,FindEntry> findPool = new WeakHashMap<>();
 
     /**
+     * The most recently used objects stored or accessed in {@link #findPool}, retained by strong references for
+     * preventing too early garbage collection. Instances put there are generally not in the {@linkplain #cache}
+     * because they are "foreigner" objects, possibly created by different authorities. Those strong references
+     * are automatically clearer in a background thread after an arbitrary delay.
+     */
+    private final ReferenceKeeper findPoolLatestQueries = new ReferenceKeeper();
+
+    /**
      * Holds the reference to a Data Access Object used by {@link ConcurrentAuthorityFactory}, together with
      * information about its usage. In a mono-thread application, there is typically only one {@code DataAccessRef}
      * instance at a given time. However if more than one than one thread are requesting new objects concurrently,
@@ -256,12 +271,16 @@ public abstract class ConcurrentAuthorityFactory<DAO extends GeodeticAuthorityFa
      * by strong references. Note that those default values may change in any future SIS versions based
      * on experience gained.
      *
-     * @param dataAccessClass The class of Data Access Object (DAO) created by {@link #newDataAccess()}.
+     * @param  dataAccessClass  the class of Data Access Object (DAO) created by {@link #newDataAccess()}.
      */
     protected ConcurrentAuthorityFactory(Class<DAO> dataAccessClass) {
         this(dataAccessClass, 100, 8);
         /*
-         * NOTE: if the default maximum number of Data Access Objects (currently 8) is augmented,
+         * NOTE 1: the number of strong references (100) seems high compared to the number of CRSs typically used,
+         * but a lot of objects are created when using the EPSG database (datum, prime meridian, parameters, axes,
+         * extents, etc).
+         *
+         * NOTE 2: if the default maximum number of Data Access Objects (currently 8) is augmented,
          * make sure to augment the number of runner threads in the "StressTest" class to a greater amount.
          */
     }
@@ -295,14 +314,20 @@ public abstract class ConcurrentAuthorityFactory<DAO extends GeodeticAuthorityFa
             }
         }
         /*
-         * Create a cache allowing key collisions.
-         * Key collision is usually an error. But in this case we allow them in order to enable recursivity.
-         * If during the creation of an object the program asks to this ConcurrentAuthorityFactory for the same
-         * object (using the same key), then the default Cache implementation considers that situation as an
-         * error unless the above property has been set to `true`.
+         * Create a cache using soft references and allowing key collisions.
+         *
+         * NOTE 1: key collision is usually an error. But in this case we allow them in order to enable recursivity.
+         * If during the creation of an object the program asks to this ConcurrentAuthorityFactory for the same object
+         * (using the same key), then the default Cache implementation considers that situation as an error unless the
+         * above property has been set to `true`.
+         *
+         * NOTE 2: the number of temporary objects created during a `search` operation is high (can be thousands),
+         * and the use of weak references may cause the next search to be almost as costly as the first search if
+         * temporary objects have been already garbage collected. We use soft references instead of weak references
+         * for avoiding that problem, because search operations occur often.
          */
         remainingDAOs = maxConcurrentQueries;
-        cache = new Cache<>(20, maxStrongReferences, false);
+        cache = new Cache<>(20, maxStrongReferences, true);
         cache.setKeyCollisionAllowed(true);
         /*
          * The shutdown hook serves two purposes:
@@ -553,7 +578,7 @@ public abstract class ConcurrentAuthorityFactory<DAO extends GeodeticAuthorityFa
      *
      * @see #close()
      */
-    final void closeExpired() {
+    private void closeExpired() {
         final List<DAO> factories;
         final boolean isEmpty;
         synchronized (availableDAOs) {
@@ -618,6 +643,10 @@ public abstract class ConcurrentAuthorityFactory<DAO extends GeodeticAuthorityFa
                 while (it.hasNext()) {
                     if (it.next().cleanup()) {
                         it.remove();
+                        /*
+                         * No need to scan `findPoolLatestQueries` for entries to remove because it
+                         * should not contain any entry with `FindEntry.explicit` flags set to `true`.
+                         */
                     }
                 }
             }
@@ -1906,6 +1935,13 @@ public abstract class ConcurrentAuthorityFactory<DAO extends GeodeticAuthorityFa
                     }
                 }
             }
+            /*
+             * Keep a strong reference to the given object, potentially overwriting oldest strong reference.
+             * The purpose is only to prevent too early invalidation of weak references in `findPool` cache.
+             * We keep a strong reference only for the top-level object, not for the intermediate searches,
+             * because strong references to intermediate objects already exist in the top-level object.
+             */
+            ((ConcurrentAuthorityFactory<?>) factory).findPoolLatestQueries.markAsUsed(object);
             return candidate;
         }
     }
diff --git a/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/IdentifiedObjectFinder.java b/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/IdentifiedObjectFinder.java
index 469d90d..8858a50 100644
--- a/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/IdentifiedObjectFinder.java
+++ b/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/IdentifiedObjectFinder.java
@@ -58,7 +58,7 @@ import org.apache.sis.util.Utilities;
  * is thread-safe. If concurrent searches are desired, then a new instance should be created for each thread.
  *
  * @author  Martin Desruisseaux (IRD, Geomatys)
- * @version 0.8
+ * @version 1.1
  *
  * @see GeodeticAuthorityFactory#newIdentifiedObjectFinder()
  * @see IdentifiedObjects#newFinder(String)
@@ -302,7 +302,7 @@ public class IdentifiedObjectFinder {
             final AuthorityFactoryProxy<?> previous = proxy;
             proxy = AuthorityFactoryProxy.getInstance(object.getClass());
             try {
-                if (!ignoreIdentifiers && !ignoreAxes) {
+                if (!ignoreIdentifiers) {
                     /*
                      * First check if one of the identifiers can be used to find directly an identified object.
                      * Verify that the object that we found is actually equal to given one; we do not blindly
diff --git a/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/ReferenceKeeper.java b/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/ReferenceKeeper.java
new file mode 100644
index 0000000..c03788c
--- /dev/null
+++ b/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/ReferenceKeeper.java
@@ -0,0 +1,151 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.referencing.factory;
+
+import org.opengis.referencing.IdentifiedObject;
+import org.apache.sis.internal.system.DelayedExecutor;
+import org.apache.sis.internal.system.DelayedRunnable;
+import org.apache.sis.internal.util.StandardDateFormat;
+
+
+/**
+ * Most recently used objects stored or accessed in {@link ConcurrentAuthorityFactory#findPool},
+ * retained by strong references for preventing too early garbage collection.
+ *
+ * <h2>Design notes</h2>
+ * <ul>
+ *   <li>Elements in this collection are generally not in {@link ConcurrentAuthorityFactory#cache}
+ *       because they are "foreigner" objects, possibly created by different authorities.
+ *       We have to maintain them in a separated collection.</li>
+ *   <li>We have to be careful about the references kept in this object. The purpose is to prevent garbage collection,
+ *       so {@link Object#equals(Object)} is not the appropriate contract for deciding which elements to put.
+ *       For example a call to {@code Map.put(key, value)} may update the value without replacing the key if an
+ *       entry already exists in the map, in which case the instance that is protected against garbage collection
+ *       is not the intended one.</li>
+ *   <li>We tried to use {@link java.util.LinkedHashMap} as a LRU map in a previous version.
+ *       It was not really simpler because of above-cited issue with object identities.</li>
+ * </ul>
+ *
+ * @author  Martin Desruisseaux (Geomatys)
+ * @version 1.1
+ * @since   1.1
+ * @module
+ */
+final class ReferenceKeeper {
+    /**
+     * Number of references to keep. Should be relatively small because this class implementation
+     * is not designed for large collections. Note that the number of unique entries may be lower
+     * because this class does not try to avoid duplicated references.
+     */
+    private static final int CAPACITY = 40;
+
+    /**
+     * Time to wait before to remove entries from this map. Current value is 5 minutes.
+     */
+    private static final long EXPIRATION_TIME = 5L * 60 * StandardDateFormat.NANOS_PER_SECOND;
+
+    /**
+     * The objects to retain by strong reference. May contains duplicated values and {@code null} anywhere.
+     * This is used as a cyclic queue. We use an array instead of {@link java.util.LinkedHashMap} for more
+     * control on which instance is retained (objet identity matter, not just object equality).
+     */
+    private IdentifiedObject[] cache;
+
+    /**
+     * Time where object references were stored in this object.
+     * Used for finding which references expired.
+     */
+    private long[] timestamps;
+
+    /**
+     * Index of the last element stored in the {@link #cache} array.
+     */
+    private int indexOfLast;
+
+    /**
+     * Whether a cleaner task has already been registered for removing oldest entries.
+     */
+    private boolean hasCleanerTask;
+
+    /**
+     * Constructs an initially empty instance.
+     */
+    ReferenceKeeper() {
+    }
+
+    /**
+     * Retains the given object by strong reference for a limited amount of time.
+     *
+     * @param  object  the object to temporarily retain by strong reference.
+     */
+    final synchronized void markAsUsed(final IdentifiedObject object) {
+        if (cache == null) {
+            cache = new IdentifiedObject[CAPACITY];
+            timestamps = new long[CAPACITY];
+        }
+        final Long now = System.nanoTime();
+        if (cache[indexOfLast] != object) {
+            if (++indexOfLast >= CAPACITY) {
+                indexOfLast = 0;
+            }
+        }
+        cache[indexOfLast] = object;
+        timestamps[indexOfLast] = now;
+        if (!hasCleanerTask) {
+            scheduleCleanerTask(now);
+        }
+    }
+
+    /**
+     * Registers a task to be executed later for removing expired entries.
+     * It is caller responsibility to verify that this method should be invoked.
+     *
+     * @param  now  value of {@link System#nanoTime()}.
+     */
+    private void scheduleCleanerTask(final long now) {
+        DelayedExecutor.schedule(new DelayedRunnable(now + EXPIRATION_TIME) {
+            @Override public void run() {
+                clearExpiredEntries();
+            }
+        });
+        hasCleanerTask = true;
+    }
+
+    /**
+     * Invoked in a background thread for clearing expired entries.
+     * This will allow the garbage collector to remove the entries from
+     * {@link ConcurrentAuthorityFactory#findPool} if not used elsewhere.
+     */
+    private synchronized void clearExpiredEntries() {
+        hasCleanerTask = false;
+        boolean empty = true;
+        final long now = System.nanoTime();
+        for (int i=0; i<CAPACITY; i++) {
+            if (now - timestamps[i] >= EXPIRATION_TIME) {
+                cache[i] = null;
+            } else {
+                empty &= (cache[i] == null);
+            }
+        }
+        if (empty) {
+            cache = null;
+            timestamps = null;
+        } else {
+            scheduleCleanerTask(now);
+        }
+    }
+}
diff --git a/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/CoordinateOperationFinder.java b/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/CoordinateOperationFinder.java
index 9aa0f59..8997504 100644
--- a/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/CoordinateOperationFinder.java
+++ b/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/CoordinateOperationFinder.java
@@ -973,8 +973,8 @@ public class CoordinateOperationFinder extends CoordinateOperationRegistry {
             if (stepComponents.length == 1) {
                 stepSourceCRS = stepComponents[0];    // Slight optimization of the next block (in the `else` case).
             } else {
-                stepSourceCRS = toAuthorityDefinition(CoordinateReferenceSystem.class,
-                        factorySIS.getCRSFactory().createCompoundCRS(derivedFrom(sourceCRS), stepComponents));
+                CompoundCRS crs = factorySIS.getCRSFactory().createCompoundCRS(derivedFrom(sourceCRS), stepComponents);
+                stepSourceCRS = toAuthorityDefinition(CoordinateReferenceSystem.class, crs);
             }
             operation = createFromAffineTransform(AXIS_CHANGES, sourceCRS, stepSourceCRS, select);
         }
@@ -1091,8 +1091,10 @@ public class CoordinateOperationFinder extends CoordinateOperationRegistry {
     private CoordinateReferenceSystem createCompoundCRS(final CoordinateReferenceSystem template,
             final CoordinateReferenceSystem[] components) throws FactoryException
     {
-        EllipsoidalHeightCombiner c = new EllipsoidalHeightCombiner(factorySIS.getCRSFactory(), factorySIS.getCSFactory(), factory);
-        return toAuthorityDefinition(CoordinateReferenceSystem.class, c.createCompoundCRS(derivedFrom(template), components));
+        EllipsoidalHeightCombiner c = new EllipsoidalHeightCombiner(
+                factorySIS.getCRSFactory(), factorySIS.getCSFactory(), factory);
+        CoordinateReferenceSystem crs = c.createCompoundCRS(derivedFrom(template), components);
+        return toAuthorityDefinition(CoordinateReferenceSystem.class, crs);
     }
 
     /**
diff --git a/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/CoordinateOperationRegistry.java b/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/CoordinateOperationRegistry.java
index 7b8a5af..505f3ec 100644
--- a/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/CoordinateOperationRegistry.java
+++ b/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/CoordinateOperationRegistry.java
@@ -159,6 +159,14 @@ class CoordinateOperationRegistry {
      * The object to use for finding authority codes, or {@code null} if none.
      * An instance is fetched at construction time from the {@link #registry} if possible.
      *
+     * <div class="note"><b>Design note:</b>
+     * using a provider defined by the {@link #registry} instead than {@code MultiAuthoritiesFactory} may cause
+     * the finder to perform extensive searches because it does not recognize the authority code of a given CRS.
+     * For example if {@link #registry} is for EPSG and a given CRS is "CRS:84", then {@code codeFinder} would
+     * not recognize the given CRS and would search for a match in the EPSG database. This is desired because
+     * we need to have the two CRSs defined by the same authority (if possible) in order to find a predefined
+     * operation, even if an equivalent definition was provided by another authority.</div>
+     *
      * @see #authorityCodes
      * @see #findCode(CoordinateReferenceSystem)
      */
@@ -249,7 +257,6 @@ class CoordinateOperationRegistry {
                 recoverableException("<init>", e);
             }
             if (codeFinder != null) {
-                codeFinder.setIgnoringAxes(true);
                 authorityCodes = new IdentityHashMap<>(5);          // Rarely more than 4 entries.
             }
         }
@@ -271,7 +278,6 @@ class CoordinateOperationRegistry {
         if (codeFinder != null) {
             codeFinder.setIgnoringAxes(false);
             final IdentifiedObject candidate = codeFinder.findSingleton(object);
-            codeFinder.setIgnoringAxes(true);
             if (Utilities.equalsIgnoreMetadata(object, candidate)) {
                 return type.cast(candidate);
             }
@@ -293,6 +299,7 @@ class CoordinateOperationRegistry {
         if (codes == null) {
             codes = new ArrayList<>();
             if (codeFinder != null) {
+                codeFinder.setIgnoringAxes(true);
                 for (final IdentifiedObject candidate : codeFinder.find(crs)) {
                     final Identifier identifier = IdentifiedObjects.getIdentifier(candidate, registry.getAuthority());
                     if (identifier != null) {
diff --git a/core/sis-utility/src/main/java/org/apache/sis/internal/util/StandardDateFormat.java b/core/sis-utility/src/main/java/org/apache/sis/internal/util/StandardDateFormat.java
index 9f9cc38..83e382e 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/internal/util/StandardDateFormat.java
+++ b/core/sis-utility/src/main/java/org/apache/sis/internal/util/StandardDateFormat.java
@@ -242,13 +242,13 @@ replace:    if (Character.isWhitespace(c)) {
      * Number of nanoseconds in one millisecond.
      * Can be casted to {@code float} with exact precision.
      */
-    public static final int NANOS_PER_MILLISECOND = 1000000;
+    public static final int NANOS_PER_MILLISECOND = 1000_000;
 
     /**
      * Number of nanoseconds in one second.
      * Can be casted to {@code float} with exact precision.
      */
-    public static final int NANOS_PER_SECOND = 1000000000;
+    public static final int NANOS_PER_SECOND = 1000_000_000;
 
     /**
      * Converts the given legacy {@code Date} object into a {@code java.time} implementation in given timezone.
diff --git a/core/sis-utility/src/main/java/org/apache/sis/util/collection/Cache.java b/core/sis-utility/src/main/java/org/apache/sis/util/collection/Cache.java
index 469f183..660fab6 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/util/collection/Cache.java
+++ b/core/sis-utility/src/main/java/org/apache/sis/util/collection/Cache.java
@@ -1176,14 +1176,22 @@ public class Cache<K,V> extends AbstractMap<K,V> implements ConcurrentMap<K,V> {
     /**
      * Invoked in a background thread after a value has been set in the map.
      * This method computes a cost estimation of the new value. If the total cost is greater
-     * than the cost limit, then oldest strong references are replaced by weak references.
+     * than the cost limit, then oldest strong references are replaced by weak references
+     * until the cost of entries kept by strong references become lower than the threshold.
      */
-    final void adjustReferences(final K key, final V value) {
+    private void adjustReferences(final K key, final V value) {
         int cost = (value != null) ? cost(value) : 0;
         synchronized (costs) {
             final Integer old = costs.put(key, cost);
             if (old != null) {
                 cost -= old;
+                /*
+                 * This block exists for more safety but should never be executed. If execution happens anyway,
+                 * the instance in the `costs` map may still the old one (depending on `HashMap` implementation),
+                 * not the new instance given as `key` argument. It may be a problem if we rely on this instance
+                 * for preventing the cleaning of weak references. It should nevertheless be okay because the
+                 * `costs` map is used for `Cache` entries that are not yet weak references.
+                 */
             }
             if ((totalCost += cost) > costLimit) {
                 final Iterator<Map.Entry<K,Integer>> it = costs.entrySet().iterator();