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

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

commit fa9f16abb48e6bac9e0af7fd9f446fe3434d111c
Author: Martin Desruisseaux <[email protected]>
AuthorDate: Mon Nov 16 15:15:48 2026 +0100

    Generalize the support of `TileObserver` to some non-writable images.
    Apply fill values to `AggregatedImage` pixels that are outside all sources.
---
 .../main/org/apache/sis/image/AggregatedImage.java | 111 ++++++++++-----
 .../main/org/apache/sis/image/BandSelectImage.java |  11 --
 .../main/org/apache/sis/image/ComputedImage.java   | 133 ++++++++++++------
 .../main/org/apache/sis/image/ComputedTiles.java   |  93 +++++++++----
 .../main/org/apache/sis/image/ImageProcessor.java  |  15 +-
 .../main/org/apache/sis/image/MonolithicImage.java | 110 +++++++++++----
 .../main/org/apache/sis/image/PlanarImage.java     | 151 ++++++++++++++++++++-
 .../apache/sis/image/WritableComputedImage.java    |  50 -------
 .../sis/image/internal/shared/FillValues.java      |  17 ++-
 .../image/internal/shared/WritableTiledImage.java  |  15 +-
 .../internal/shared/WritableUntiledImage.java      |   4 +-
 .../org/apache/sis/image/AggregatedImageTest.java  | 102 ++++++++++++--
 .../test/org/apache/sis/image/TiledImageMock.java  |  15 --
 13 files changed, 600 insertions(+), 227 deletions(-)

diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/AggregatedImage.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/AggregatedImage.java
index 35061e1bb3..f1e772fb8a 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/AggregatedImage.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/AggregatedImage.java
@@ -16,6 +16,8 @@
  */
 package org.apache.sis.image;
 
+import java.util.Map;
+import java.util.LinkedHashMap;
 import java.util.BitSet;
 import java.util.Vector;
 import java.util.Arrays;
@@ -40,6 +42,7 @@ import org.opengis.referencing.operation.TransformException;
 import org.apache.sis.referencing.operation.transform.MathTransforms;
 import org.apache.sis.image.internal.shared.WritableTiledImage;
 import org.apache.sis.image.internal.shared.ImageUtilities;
+import org.apache.sis.image.internal.shared.FillValues;
 import org.apache.sis.coverage.grid.PixelInCell;
 import org.apache.sis.pending.jdk.JDK18;
 import org.apache.sis.system.CommonExecutor;
@@ -149,9 +152,9 @@ public class AggregatedImage extends MonolithicImage 
implements Disposable {
     protected final SampleModel sampleModel;
 
     /**
-     * The values to use if the source images provide no value.
+     * The fill values in a helper class for filling new tiles to that value.
      */
-    private final double[] fillValues;
+    private final FillValues filler;
 
     /**
      * Number of bands in which some values will be aggregated.
@@ -220,7 +223,7 @@ public class AggregatedImage extends MonolithicImage 
implements Disposable {
      * @param  layout       preferences about how to derive a sample model for 
this aggregated image.
      * @param  bounds       domain of pixel coordinates of this aggregated 
image, or {@code null} for automatic.
      * @param  aggregation  the method to use for performing aggregations.
-     * @param  fillValues   the values to use if the source images have 
missing bands, or {@code null} for NaNs.
+     * @param  fillValues   the values to use for sample values not covered by 
a source.
      * @throws TransformException if {@code bounds} is null and an error 
occurred while computing automatic bounds.
      */
     public AggregatedImage(Source[] sources,
@@ -276,17 +279,7 @@ public class AggregatedImage extends MonolithicImage 
implements Disposable {
         if (effectiveNumBands >= Integer.MAX_VALUE / (CHUNK_SIZE * CHUNK_SIZE 
* NUM_ACCUMULATORS)) {
             throw new 
RasterFormatException(Errors.format(Errors.Keys.IllegalPropertyValue_2, 
"numBands", effectiveNumBands));
         }
-        final var values = new double[sampleModel.getNumBands()];
-        Arrays.fill(values, Double.NaN);
-        if (fillValues != null) {
-            for (int i = Math.min(values.length, fillValues.length); --i >= 
0;) {
-                final Number value = fillValues[i];
-                if (value != null) {
-                    values[i] = value.doubleValue();
-                }
-            }
-        }
-        this.fillValues = values;
+        filler = new FillValues(sampleModel, fillValues, true);
     }
 
     /**
@@ -482,11 +475,12 @@ public class AggregatedImage extends MonolithicImage 
implements Disposable {
         final int chunksPerImageRow = numChunks(width);
         final int chunkCellStride = effectiveNumBands * NUM_ACCUMULATORS;
         final var bounds = new Rectangle(CHUNK_SIZE, CHUNK_SIZE);
+        final double[] fillValues = filler.asDoubles();
         final double[] samples = fillValues.clone();
         final var writable = new WriteAdapter(
-                getSampleModel(),
+                sampleModel,
                 new Rectangle(minX, minY, width, height),
-                new Point(minTileX, minTileY), numXTiles,
+                new Point(minTileX, minTileY),
                 tiles, dirtyTiles);
 
         for (int i=0; i<data.length; i++) {
@@ -516,8 +510,12 @@ public class AggregatedImage extends MonolithicImage 
implements Disposable {
                                 samples[j] = (num != 0) ? sum/num : 
fillValues[j];
                             }
                             it.setPixel(samples);
+                        } else {
+                            valueIndex += chunkCellStride;      // Skip the 
pixel without writing it.
                         }
                     }
+                } finally {
+                    writable.fireTilesUpdated();
                 }
             }
         }
@@ -529,38 +527,84 @@ public class AggregatedImage extends MonolithicImage 
implements Disposable {
      * should be written. Non-dirty tiles should not be modified because all 
needed
      * source tiles may not have been scanned.
      */
-    private static final class WriteAdapter extends WritableTiledImage {
-        /** Whether the current tile should be updated. */
+    private final class WriteAdapter extends WritableTiledImage {
+        /**
+         * Whether the current tile should be updated.
+         * If {@code false}, {@link AggregatedImage} shall not update the 
current tile.
+         * Skipping such tiles is necessary otherwise their content would be 
corrupted because
+         * of incomplete aggregated data when only a subset of the sources 
have been scanned.
+         * This flag is updated when the pixel iterator moves from one tile to 
another.
+         */
         boolean dirtyTile;
 
-        /** List of all dirty tiles, or {@code null} for all. */
+        /**
+         * Row-major indexes of dirty tiles, or {@code null} if all tiles need 
to be computed.
+         */
         private final BitSet dirtyTiles;
 
-        /** Copy of {@link AggregatedImage#numXTiles}. */
-        private final int numXTiles;
+        /**
+         * Indexes of tiles which are updated, together with whether to notify 
the listener.
+         * The values are {@code false} when a tile is created for the first 
time.
+         */
+        private final Map<Point, Boolean> updatedTiles;
 
-        /** Creates a new adapter for writing a tile. */
+        /**
+         * Creates a new adapter for writing the tiles of the enclosing 
aggregated image.
+         * This is an adapter for allowing the use of {@link 
WritablePixelIterator}.
+         */
         WriteAdapter(final SampleModel sampleModel,
                      final Rectangle   bounds,
                      final Point       minTile,
-                     final int         numXTiles,
                      final WritableRaster[] tiles,
                      final BitSet dirtyTiles)
         {
             super(null, null, sampleModel, bounds, minTile, tiles);
             this.dirtyTiles = dirtyTiles;
-            this.numXTiles  = numXTiles;
-            dirtyTile = (dirtyTiles == null);
+            updatedTiles = new LinkedHashMap<>();
         }
 
-        /** Gets a writable tile and set the flag saying whether this tile 
should be updated. */
-        @Override public WritableRaster getWritableTile(final int tileX, final 
int tileY) {
-            if (dirtyTiles != null) {
-                final int tileIndex = (tileY - minTileY) * numXTiles + (tileX 
- minTileX);
-                dirtyTile = dirtyTiles.get(tileIndex);
+        /**
+         * Creates an initially empty tile filled with the fill value.
+         */
+        @Override
+        protected WritableRaster createTile(final Point location) {
+            final WritableRaster tile = super.createTile(location);
+            if (!filler.isFullyZero) filler.fill(tile);
+            return tile;
+        }
+
+        /**
+         * Gets a writable tile and set the flag saying whether this tile 
should be updated.
+         * If {@link #dirtyTile} is {@code false} after the invocation of this 
method, then
+         * the caller shall not update the current tile.
+         */
+        @Override
+        public WritableRaster getWritableTile(final int tileX, final int 
tileY) {
+            final int tileIndex = (tileY - minTileY) * numXTiles + (tileX - 
minTileX);
+            dirtyTile = (dirtyTiles == null) || dirtyTiles.get(tileIndex);
+            if (dirtyTile) {
+                final boolean tileExists = (tiles[tileIndex] != null);
+                if (updatedTiles.putIfAbsent(new Point(tileX, tileY), 
tileExists) == null && tileExists) {
+                    fireTileUpdate(tileX, tileY, true);
+                }
             }
             return super.getWritableTile(tileX, tileY);
         }
+
+        /**
+         * Notifies listeners after we are sure that the tile updates are 
finished.
+         * We wait until the iteration finished because the same tiles may be 
acquired, released,
+         * then acquired again many times, and we want to notify the listeners 
only once.
+         */
+        final void fireTilesUpdated() {
+            for (final Map.Entry<Point, Boolean> entry : 
updatedTiles.entrySet()) {
+                if (entry.getValue()) {
+                    final Point tile = entry.getKey();
+                    fireTileUpdate(tile.x, tile.y, false);
+                }
+            }
+            updatedTiles.clear();
+        }
     }
 
     /**
@@ -794,8 +838,11 @@ images:     while (imageIndex < upperImageIndex) {
                                         }
                                         int valueIndex = cellIndex * 
chunkValueStride;
                                         for (int j=0; j<numBands; j++) {
-                                            dataChunk[valueIndex++] += weight 
* sampleValues[j];
-                                            dataChunk[valueIndex++] += weight;
+                                            final double value = 
sampleValues[j];
+                                            if (!Double.isNaN(value)) {
+                                                dataChunk[valueIndex++] += 
weight * value;
+                                                dataChunk[valueIndex++] += 
weight;
+                                            }
                                         }
                                     }
                                 }
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/BandSelectImage.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/BandSelectImage.java
index ffc1441ef0..5539e57eca 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/BandSelectImage.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/BandSelectImage.java
@@ -27,7 +27,6 @@ import java.awt.image.RenderedImage;
 import java.awt.image.WritableRaster;
 import java.awt.image.WritableRenderedImage;
 import java.awt.image.ColorModel;
-import java.awt.image.TileObserver;
 import org.apache.sis.util.ArraysExt;
 import org.apache.sis.util.ArgumentChecks;
 import org.apache.sis.image.internal.shared.ImageUtilities;
@@ -272,16 +271,6 @@ class BandSelectImage extends SourceAlignedImage {
             markTileWritable(tileX, tileY, false);
         }
 
-        /** Adds an observer to be notified when a tile is checked out for 
writing. */
-        @Override public void addTileObserver(final TileObserver observer) {
-            target().addTileObserver(observer);
-        }
-
-        /** Removes an observer from the list of observers notified when a 
tile is checked out for writing. */
-        @Override public void removeTileObserver(final TileObserver observer) {
-            target().removeTileObserver(observer);
-        }
-
         /** Sets a region of the image to the contents of the given raster. */
         @Override public void setData(final Raster data) {
             final WritableRenderedImage target = target();
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ComputedImage.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ComputedImage.java
index 9431daf604..7a479b5f6a 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ComputedImage.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ComputedImage.java
@@ -33,7 +33,6 @@ import java.awt.image.SampleModel;
 import java.awt.image.TileObserver;
 import java.awt.image.ImagingOpException;
 import org.apache.sis.util.ArgumentChecks;
-import org.apache.sis.util.ArraysExt;
 import org.apache.sis.util.Disposable;
 import org.apache.sis.util.Exceptions;
 import org.apache.sis.util.internal.shared.Numerics;
@@ -42,6 +41,7 @@ import org.apache.sis.util.resources.Errors;
 import org.apache.sis.coverage.grid.GridExtent;     // For javadoc
 import org.apache.sis.feature.internal.Resources;
 import org.apache.sis.image.internal.shared.ImageUtilities;
+import org.apache.sis.image.internal.shared.WritableUntiledImage;
 
 
 /**
@@ -53,9 +53,9 @@ import org.apache.sis.image.internal.shared.ImageUtilities;
  *
  * <p>{@code ComputedImage} may have an arbitrary number of source images, 
including zero.
  * A {@link TileObserver} is automatically registered to all sources that are 
instances of
- * {@link WritableRenderedImage}. If one of those sources sends a change 
event, then all
- * {@code ComputedImage} tiles that may be impacted by that change are marked 
as <dfn>dirty</dfn>
- * and will be computed again when needed.</p>
+ * {@link WritableRenderedImage} or {@link PlanarImage}.
+ * If one of those sources sends a change event, then all {@code 
ComputedImage} tiles that may be
+ * impacted by that change are marked as <dfn>dirty</dfn> and will be computed 
again when needed.</p>
  *
  * <p>When this {@code ComputedImage} is garbage collected, all cached tiles 
are discarded
  * and the above-cited {@link TileObserver} is automatically removed from all 
sources.
@@ -117,7 +117,8 @@ import org.apache.sis.image.internal.shared.ImageUtilities;
  * if the change to dirty state happened after the call to {@link 
#getTile(int, int) getTile(…)}.</p>
  *
  * @author  Martin Desruisseaux (Geomatys)
- * @version 1.7
+ * @version 1.8
+ *
  * @since SIS 1.1
  */
 public abstract class ComputedImage extends PlanarImage implements Disposable {
@@ -210,12 +211,26 @@ public abstract class ComputedImage extends PlanarImage 
implements Disposable {
      */
     protected final SampleModel sampleModel;
 
+    /**
+     * The observers, or {@code null} if none. This is a copy-on-write array:
+     * values are never modified after construction (new arrays are created).
+     *
+     * This field is declared volatile because it is read without 
synchronization by
+     * {@link #markTileWritable(int, int, boolean)}. Since this is a 
copy-on-write array,
+     * it is okay to omit synchronization for that method but we still need 
the memory effect.
+     *
+     * @see #addTileObserver(TileObserver)
+     * @see #removeTileObserver(TileObserver)
+     */
+    @SuppressWarnings("VolatileArrayField")
+    private volatile TileObserver[] observers;
+
     /**
      * Creates an initially empty image with the given sample model.
      * The default tile size will be the width and height of the given sample 
model
      * (this default setting minimizes the amount of memory consumed by {@link 
#createTile(int, int)}).
-     * This constructor automatically registers a {@link TileObserver}
-     * for all sources that are {@link WritableRenderedImage} instances.
+     * This constructor automatically registers a {@link TileObserver} for all 
sources that are
+     * instances of {@link WritableRenderedImage} or {@link PlanarImage}.
      *
      * @param  sampleModel  the sample model shared by all tiles in this image.
      * @param  sources      sources of this image (may be an empty array), or 
a null array if unknown.
@@ -223,40 +238,14 @@ public abstract class ComputedImage extends PlanarImage 
implements Disposable {
     @SuppressWarnings("this-escape")        // `this` escaped as weak 
reference only.
     protected ComputedImage(final SampleModel sampleModel, RenderedImage... 
sources) {
         this.sampleModel = Objects.requireNonNull(sampleModel);
-        /*
-         * Verify the `sources` argument validity and opportunistically 
collect all writable sources
-         * in a separated array. If at the end it appears that the two arrays 
have the same content,
-         * the same array will be shared by this `ComputedImage` and its 
`TileObserver`.
-         */
-        WritableRenderedImage[] ws = null;
         if (sources != null) {
             sources = sources.clone();
-            int count = 0;
             for (int i=0; i<sources.length; i++) {
-                final RenderedImage source = sources[i];
-                ArgumentChecks.ensureNonNullElement("sources", i, source);
-                if (source instanceof WritableRenderedImage) {
-                    if (ws == null) {
-                        ws = new WritableRenderedImage[sources.length - i];
-                    }
-                    ws[count++] = (WritableRenderedImage) source;
-                }
-            }
-            /*
-             * If `count` is 0, then `ws` is null while `sources` is non-null. 
This is intentional:
-             * a null `sources` array does not have the same meaning as an 
empty `sources` array.
-             * In the case of `ws` however, the difference does not matter so 
we keep it to null.
-             */
-            if (count != 0) {
-                if (count == sources.length) {
-                    sources = ws;                   // The two arrays have the 
same content; share the same array.
-                } else {
-                    ws = ArraysExt.resize(ws, count);
-                }
+                ArgumentChecks.ensureNonNullElement("sources", i, sources[i]);
             }
         }
-        this.sources = sources;                     // Note: null value does 
not have same meaning as empty array.
-        reference = new ComputedTiles(this, ws);    // Create cleaner last 
after all arguments have been validated.
+        this.sources = sources;                         // Note: null value 
does not have same meaning as empty array.
+        reference = new ComputedTiles(this, sources);   // Create cleaner last 
after all arguments have been validated.
     }
 
     /**
@@ -511,6 +500,7 @@ public abstract class ComputedImage extends PlanarImage 
implements Disposable {
                     /*
                      * Actual computation.
                      */
+                    fireTileUpdate(tileX, tileY, true);
                     try {
                         tile = computeTile(tileX, tileY, previous);
                     } catch (Exception e) {
@@ -521,6 +511,7 @@ public abstract class ComputedImage extends PlanarImage 
implements Disposable {
                             destination.releaseWritableTile(tileX, tileY);
                         }
                     }
+                    fireTileUpdate(tileX, tileY, false);
                     if (marked) {
                         reference.endWrite(key, error == null);
                     }
@@ -680,7 +671,7 @@ public abstract class ComputedImage extends PlanarImage 
implements Disposable {
     }
 
     /**
-     * Sets or clears whether a tile is checked out for writing.
+     * Sets or clears whether a tile is checked out for writing and notifies 
the listeners if needed.
      * This method is provided for subclasses that implement the {@link 
WritableRenderedImage} interface.
      * This method can be used as below:
      *
@@ -714,12 +705,17 @@ public abstract class ComputedImage extends PlanarImage 
implements Disposable {
      * @see WritableRenderedImage#releaseWritableTile(int, int)
      */
     protected boolean markTileWritable(final int tileX, final int tileY, final 
boolean writing) {
-        final TileCache.Key key = new TileCache.Key(reference, tileX, tileY);
+        final var key = new TileCache.Key(reference, tileX, tileY);
+        final boolean notify;
         if (writing) {
-            return reference.startWrite(key);
+            notify = reference.startWrite(key);
         } else {
-            return reference.endWrite(key, true);
+            notify = reference.endWrite(key, true);
         }
+        if (notify) {
+            fireTileUpdate(tileX, tileY, writing);
+        }
+        return notify;
     }
 
     /**
@@ -731,8 +727,8 @@ public abstract class ComputedImage extends PlanarImage 
implements Disposable {
      * <p>Subclasses can invoke this method when the tiles in the given range 
depend on source data
      * that changed, typically (but not necessarily) {@linkplain #getSources() 
source images}.
      * Note that there is no need to invoke this method if the source images 
are instances of
-     * {@link WritableRenderedImage}, because {@code ComputedImage} already 
has {@link TileObserver}
-     * for them.</p>
+     * {@link WritableRenderedImage} or {@link PlanarImage},
+     * because {@code ComputedImage} already has {@link TileObserver} for 
them.</p>
      *
      * @param  tiles  indices of tiles to mark as dirty.
      * @return {@code true} if at least one tile has been marked dirty.
@@ -774,6 +770,59 @@ public abstract class ComputedImage extends PlanarImage 
implements Disposable {
                           Math.addExact(tiles.y, tiles.height - 1));
     }
 
+    /**
+     * Adds an observer to be notified when a tile is about to be modified.
+     * A tile can be modified directly if this image implements the {@link 
WritableRenderedImage} interface
+     * and a tile has been acquired for writing, or indirectly if this image 
is computed from other sources
+     * and one of the source images changed. In the latter case, the given 
listener should be an instance of
+     * {@link Observer} in order to be notified even if this image is not a 
{@link WritableRenderedImage},
+     *
+     * @param  observer  the observer to notify, ignored if {@code null}.
+     *         If already present, it will receive multiple notifications.
+     *
+     * @see WritableRenderedImage#addTileObserver(TileObserver)
+     * @see Observer
+     *
+     * @since SIS 1.8
+     */
+    @Override
+    public synchronized void addTileObserver(final TileObserver observer) {
+        if (observer instanceof Observer || this instanceof 
WritableRenderedImage) {
+            observers = WritableUntiledImage.addTileObserver(observers, 
observer);
+        }
+    }
+
+    /**
+     * Removes an observer from the list of observers notified when a tile is 
modified.
+     * If the observer was not registered, nothing happens.
+     * If the observer was registered for multiple notifications, it will now 
be registered for one fewer.
+     *
+     * <p>The default implementation does nothing except ensuring that the 
argument is non-null.
+     * This method is overridden by subclasses such as {@link ComputedImage}, 
{@link AggregatedImage}
+     * and all writable images.</p>
+     *
+     * @param  observer  the observer to stop notifying.
+     *
+     * @see WritableRenderedImage#removeTileObserver(TileObserver)
+     *
+     * @since SIS 1.8
+     */
+    @Override
+    public synchronized void removeTileObserver(final TileObserver observer) {
+        observers = WritableUntiledImage.removeTileObserver(observers, 
observer);
+    }
+
+    /**
+     * Notifies listeners that a tile is about to be modified or has been 
modified.
+     *
+     * @param  tileX    the <var>x</var> index of the tile to acquire or 
release.
+     * @param  tileY    the <var>y</var> index of the tile to acquire or 
release.
+     * @param  writing  {@code true} if the tile will be modified, or {@code 
false} if the modification is done.
+     */
+    private void fireTileUpdate(final int tileX, final int tileY, final 
boolean writing) {
+        fireTileUpdate(observers, this, tileX, tileY, writing);
+    }
+
     /**
      * Invoked when a tile of a source image has been updated. This method 
should {@linkplain #markDirtyTiles
      * mark as dirty} all tiles of this {@code ComputedImage} that depend on 
the updated tile.
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ComputedTiles.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ComputedTiles.java
index 601d9de077..225dbdd6d4 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ComputedTiles.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ComputedTiles.java
@@ -19,15 +19,19 @@ package org.apache.sis.image;
 import java.util.Map;
 import java.util.HashMap;
 import java.util.List;
+import java.util.Arrays;
 import java.lang.ref.WeakReference;
+import java.lang.reflect.UndeclaredThrowableException;
 import java.awt.Point;
 import java.awt.Rectangle;
 import java.awt.image.TileObserver;
+import java.awt.image.RenderedImage;
 import java.awt.image.ImagingOpException;
-import java.awt.image.WritableRenderedImage;
 import org.apache.sis.feature.internal.Resources;
 import org.apache.sis.system.ReferenceQueueConsumer;
+import org.apache.sis.image.internal.shared.ImageUtilities;
 import org.apache.sis.util.Disposable;
+import org.apache.sis.util.logging.Logging;
 
 
 /**
@@ -41,7 +45,7 @@ import org.apache.sis.util.Disposable;
  *
  * @author  Martin Desruisseaux (Geomatys)
  */
-final class ComputedTiles extends WeakReference<ComputedImage> implements 
Disposable, TileObserver {
+final class ComputedTiles extends WeakReference<ComputedImage> implements 
Disposable, PlanarImage.Observer {
     /**
      * Whether a tile in the cache is ready for use or needs to be recomputed 
because one if its sources
      * changed its data. Those values are stored in {@link #cachedTiles} map.
@@ -70,10 +74,10 @@ final class ComputedTiles extends 
WeakReference<ComputedImage> implements Dispos
     private final Map<TileCache.Key, Integer> cachedTiles;
 
     /**
-     * All {@link ComputedImage#sources} that are writable, or {@code null} if 
none.
+     * All {@link ComputedImage#sources} for which a listener has been 
registered, or {@code null} if none.
      * This is used for removing tile observers when the {@link ComputedImage} 
is garbage-collected.
      */
-    private WritableRenderedImage[] sources;
+    private RenderedImage[] sources;
 
     /**
      * Creates a new weak reference to the given image and registers this 
{@link ComputedTiles}
@@ -84,23 +88,50 @@ final class ComputedTiles extends 
WeakReference<ComputedImage> implements Dispos
      * @param  ws     sources to observe for changes, or {@code null} if none.
      */
     @SuppressWarnings("LeakingThisInConstructor")
-    ComputedTiles(final ComputedImage image, final WritableRenderedImage[] ws) 
{
+    ComputedTiles(final ComputedImage image, RenderedImage[] ws) {
         super(image, ReferenceQueueConsumer.QUEUE);
         cachedTiles = new HashMap<>();
-        sources = ws;
         if (ws != null) {
-            int i = 0;
+            sources = ws;
+            ws = ws.clone();
+            int count = 0;
             try {
-                while (i < ws.length) {
-                    WritableRenderedImage source = ws[i++];     // `i++` must 
be before `addTileObserver(…)` call.
-                    source.addTileObserver(this);
+                for (final RenderedImage source : ws) {
+                    if (PlanarImage.addTileObserver(source, this) && 
!listenerWasIgnored(source)) {
+                        ws[count++] = source;
+                    }
+                }
+                if (count != ws.length) {
+                    sources = Arrays.copyOf(ws, count);
                 }
-            } catch (RuntimeException e) {
-                unregister(ws, i, e);                           // 
`unregister(…)` will rethrow the given exception.
+            } catch (Throwable e) {
+                unregister(ws, count + 1, e);   // `unregister(…)` will 
rethrow the given exception.
             }
         }
     }
 
+    /**
+     * Returns whether the given image has ignored the listener.
+     * This is used for avoiding to keep unnecessary references to source 
images in this class,
+     * for reducing the risk of memory leak (images may potentially hold large 
amount of memory).
+     *
+     * <p>This method uses reflection with the knowledge that the default 
implementation
+     * of {@link PlanarImage#addTileObserver(TileObserver)} does nothing. If 
this method
+     * has not been overridden, the listener has been ignored.</p>
+     *
+     * @param  image  the image where a listener has been added.
+     * @return whether the image has ignored the listener (determined by 
reflection.
+     */
+    private static boolean listenerWasIgnored(final RenderedImage image) {
+        if (image instanceof PlanarImage) try {
+            return image.getClass().getMethod("addTileObserver", 
TileObserver.class).getDeclaringClass() == PlanarImage.class;
+        } catch (ReflectiveOperationException e) {
+            // Should never happen. If happen anyway, conservatively assume 
that the listener is not ignored.
+            Logging.unexpectedException(ImageUtilities.LOGGER, 
PlanarImage.class, "addTileObserver", e);
+        }
+        return false;
+    }
+
     /**
      * Returns {@code true} if the given value is {@link #COMPUTING} or a 
greater unsigned value.
      * Returns {@code false} if the value is null, {@link #VALID}, {@link 
#DIRTY} or {@link #ERROR}.
@@ -310,14 +341,14 @@ final class ComputedTiles extends 
WeakReference<ComputedImage> implements Dispos
      * This method is interested only in events fired after the change is done.
      * The tiles that depend on the modified tile are marked in need to be 
recomputed.
      *
-     * @param source          the image that own the tile which is about to be 
updated.
-     * @param tileX           the <var>x</var> index of the tile that is being 
updated.
-     * @param tileY           the <var>y</var> index of the tile that is being 
updated.
-     * @param willBeWritable  if {@code true}, the tile is grabbed for 
writing; otherwise it is being released.
+     * @param source   the image that own the tile which is about to be 
updated.
+     * @param tileX    the <var>x</var> index of the tile that is being 
updated.
+     * @param tileY    the <var>y</var> index of the tile that is being 
updated.
+     * @param writing  {@code true} if the tile will be modified, or {@code 
false} if the modification is done.
      */
     @Override
-    public void tileUpdate(final WritableRenderedImage source, int tileX, int 
tileY, final boolean willBeWritable) {
-        if (!willBeWritable) {
+    public void tileUpdate(final RenderedImage source, int tileX, int tileY, 
final boolean writing) {
+        if (!writing) {
             final ComputedImage target = get();
             if (target != null) {
                 target.sourceTileChanged(source, tileX, tileY);
@@ -327,7 +358,7 @@ final class ComputedTiles extends 
WeakReference<ComputedImage> implements Dispos
                  * its work. Or maybe we have a bug in our code and this 
`ComputedTiles` is still alive when
                  * it should not. In any cases there is no point to continue 
observing the source.
                  */
-                source.removeTileObserver(this);
+                PlanarImage.removeTileObserver(source, this);
             }
         }
     }
@@ -338,10 +369,10 @@ final class ComputedTiles extends 
WeakReference<ComputedImage> implements Dispos
      * shared by many images, other images are not impacted.
      *
      * <p>This method should not perform other cleaning work because it is not 
guaranteed to be invoked.
-     * In some case, there is nothing preventing this weak reference to be 
garbage collected before this
-     * {@code dispose()} method is invoked. The case is: if {@code 
ComputedTiles} is not registered as a
-     * {@link TileObserver} and if {@link TileCache#GLOBAL} does not contain 
any tile associated with this
-     * {@link ComputedImage} in its key.</p>
+     * In some cases, this weak reference can be garbage collected before this 
{@code dispose()} method
+     * is invoked. Example: if {@code ComputedTiles} is not registered as a 
{@link PlanarImage.Observer}
+     * and if {@link TileCache#GLOBAL} does not contain any tile associated 
with the {@link ComputedImage}
+     * in its key.</p>
      *
      * @see ComputedImage#dispose()
      */
@@ -351,7 +382,7 @@ final class ComputedTiles extends 
WeakReference<ComputedImage> implements Dispos
             cachedTiles.keySet().forEach(TileCache.Key::dispose);
             cachedTiles.clear();
         }
-        final WritableRenderedImage[] ws = sources;
+        final RenderedImage[] ws = sources;
         if (ws != null) {
             unregister(ws, ws.length, null);
         }
@@ -368,16 +399,22 @@ final class ComputedTiles extends 
WeakReference<ComputedImage> implements Dispos
      * @param  i        index after the last source to stop observing.
      * @param  failure  if this method is invoked because an exception 
occurred, that exception.
      */
-    private void unregister(final WritableRenderedImage[] ws, int i, 
RuntimeException failure) {
+    private void unregister(final RenderedImage[] ws, int i, Throwable 
failure) {
         sources = null;                     // Let GC to its work in case of 
error in this method.
         while (--i >= 0) try {
-            ws[i].removeTileObserver(this);
-        } catch (RuntimeException e) {
+            PlanarImage.removeTileObserver(ws[i], this);
+        } catch (Throwable e) {
             if (failure == null) failure = e;
             else failure.addSuppressed(e);
         }
         if (failure != null) {
-            throw failure;
+            if (failure instanceof RuntimeException) {
+                throw (RuntimeException) failure;
+            } else if (failure instanceof Error) {
+                throw (Error) failure;
+            } else {
+                throw new UndeclaredThrowableException(failure);
+            }
         }
     }
 }
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageProcessor.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageProcessor.java
index 9d92d77719..0081916b28 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageProcessor.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageProcessor.java
@@ -34,6 +34,7 @@ import java.awt.image.RenderedImage;
 import java.awt.image.ImagingOpException;
 import java.awt.image.IndexColorModel;
 import java.awt.image.WritableRenderedImage;
+import java.awt.image.TileObserver;
 import javax.measure.Quantity;
 import org.opengis.referencing.operation.MathTransform;
 import org.opengis.referencing.operation.MathTransform1D;
@@ -1110,7 +1111,7 @@ public class ImageProcessor implements Cloneable {
      *
      * <p><b>Result relationship with source:</b>
      * Changes in the source image are reflected in the returned image
-     * if the source image notifies {@linkplain java.awt.image.TileObserver 
tile observers}.</p>
+     * if the source image notifies {@linkplain TileObserver tile 
observers}.</p>
      *
      * @param  source        the image for which to convert sample values.
      * @param  sourceRanges  approximate ranges of values for each band in 
source image, or {@code null} if unknown.
@@ -1180,7 +1181,7 @@ public class ImageProcessor implements Cloneable {
      *
      * <p><b>Result relationship with source:</b>
      * Changes in the source image are reflected in the returned images
-     * if the source image notifies {@linkplain java.awt.image.TileObserver 
tile observers}.</p>
+     * if the source image notifies {@linkplain TileObserver tile 
observers}.</p>
      *
      * @param  source    the image to be resampled.
      * @param  bounds    domain of pixel coordinates of resampled image to 
create. Fields are updated in-place
@@ -1280,14 +1281,14 @@ public class ImageProcessor implements Cloneable {
      * <p>This operation uses the following properties in addition to method 
parameters:</p>
      * <ul>
      *   <li>{@linkplain #getAggregation()   Aggregation method} (weighted 
average, <i>etc</i>).</li>
-     *   <li>{@linkplain #getFillValues()    Fill values} for missing bands in 
source images.</li>
+     *   <li>{@linkplain #getFillValues()    Fill values} for sample values 
not covered by a source.</li>
      *   <li>{@linkplain #getImageLayout()   Image layout} for inferring a 
sample model.</li>
      *   <li>{@linkplain #getExecutionMode() Execution mode} (parallel or 
sequential).</li>
      * </ul>
      *
      * <p><b>Result relationship with source:</b>
      * Changes in the source image will cause a recomputation of the returned 
image
-     * if the source image notifies {@linkplain java.awt.image.TileObserver 
tile observers}.</p>
+     * if the source image notifies {@linkplain TileObserver tile 
observers}.</p>
      *
      * @param  source      the image to be resampled.
      * @param  bounds      domain of pixel coordinates of the aggregated 
image, or {@code null} for automatic.
@@ -1314,14 +1315,14 @@ public class ImageProcessor implements Cloneable {
      * <p>This operation uses the following properties in addition to method 
parameters:</p>
      * <ul>
      *   <li>{@linkplain #getAggregation()   Aggregation method} (weighted 
average, <i>etc</i>).</li>
-     *   <li>{@linkplain #getFillValues()    Fill values} for missing bands in 
source images.</li>
+     *   <li>{@linkplain #getFillValues()    Fill values} for sample values 
not covered by a source.</li>
      *   <li>{@linkplain #getImageLayout()   Image layout} for inferring a 
sample model.</li>
      *   <li>{@linkplain #getExecutionMode() Execution mode} (parallel or 
sequential).</li>
      * </ul>
      *
      * <p><b>Result relationship with source:</b>
      * Changes in any source image will cause a recomputation of the returned 
image
-     * if the source images notify {@linkplain java.awt.image.TileObserver 
tile observers}.</p>
+     * if the source images notify {@linkplain TileObserver tile 
observers}.</p>
      *
      * @param  bounds   domain of pixel coordinates of the aggregated image, 
or {@code null} for automatic.
      * @param  sources  the images to aggregate with their transforms from 
<em>source</em> to <em>new</em> image.
@@ -1374,7 +1375,7 @@ public class ImageProcessor implements Cloneable {
      *
      * <p><b>Result relationship with source:</b>
      * Changes in the source image are reflected in the returned images
-     * if the source image notifies {@linkplain java.awt.image.TileObserver 
tile observers}.</p>
+     * if the source image notifies {@linkplain TileObserver tile 
observers}.</p>
      *
      * @param  source  the image for which to compute an overview.
      * @return image overview.
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/MonolithicImage.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/MonolithicImage.java
index 48933460e4..44819ee034 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/MonolithicImage.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/MonolithicImage.java
@@ -20,6 +20,7 @@ import java.lang.ref.WeakReference;
 import java.awt.image.TileObserver;
 import java.awt.image.RenderedImage;
 import java.awt.image.WritableRenderedImage;
+import org.apache.sis.image.internal.shared.WritableUntiledImage;
 
 
 /**
@@ -31,9 +32,25 @@ import java.awt.image.WritableRenderedImage;
  */
 abstract class MonolithicImage extends PlanarImage {
     /**
-     * The listener, or {@code null} if none.
+     * The observers, or {@code null} if none. This is a copy-on-write array:
+     * values are never modified after construction (new arrays are created).
+     *
+     * This field is declared volatile because it is read without 
synchronization by
+     * {@link #markTileWritable(int, int, boolean)}. Since this is a 
copy-on-write array,
+     * it is okay to omit synchronization for that method but we still need 
the memory effect.
+     *
+     * @see #addTileObserver(TileObserver)
+     * @see #removeTileObserver(TileObserver)
+     */
+    @SuppressWarnings("VolatileArrayField")
+    private volatile TileObserver[] observers;
+
+    /**
+     * The common listener registered on all source images, or {@code null} if 
none.
+     * This listener use weak reference, therefore it should not cause 
retention of
+     * large amount of memory.
      */
-    private TileObserver listener;
+    private TileObserver sourceListener;
 
     /**
      * Creates a new monolithic image.
@@ -49,39 +66,43 @@ abstract class MonolithicImage extends PlanarImage {
     abstract RenderedImage[] getSourceImages();
 
     /**
-     * Removes the listener from all images that are writable.
+     * Adds a listener by weak reference to all images that are writable or 
planar.
      * This method should be invoked in a synchronized block.
      */
-    final void unregisterSourceListeners() {
-        if (listener != null) {
+    final void registerSourceListeners() {
+        boolean registered = false;
+        TileObserver listener = sourceListener;
+        try {
             for (final RenderedImage source : getSourceImages()) {
-                if (source instanceof WritableRenderedImage) {
-                    ((WritableRenderedImage) 
source).removeTileObserver(listener);
+                if (listener == null) {
+                    listener = new Listener(this);
                 }
+                registered |= addTileObserver(source, listener);
+            }
+        } finally {
+            if (registered) {
+                sourceListener = listener;
             }
-            listener = null;
         }
     }
 
     /**
-     * Adds a listener by weak reference to all images that are writable.
+     * Removes the listener from all images that are writable or planar.
      * This method should be invoked in a synchronized block.
      */
-    final void registerSourceListeners() {
-        for (final RenderedImage source : getSourceImages()) {
-            if (source instanceof WritableRenderedImage) {
-                if (listener == null) {
-                    listener = new Listener(this);
-                }
-                ((WritableRenderedImage) source).addTileObserver(listener);
+    final void unregisterSourceListeners() {
+        if (sourceListener != null) {
+            for (final RenderedImage source : getSourceImages()) {
+                removeTileObserver(source, sourceListener);
             }
+            sourceListener = null;
         }
     }
 
     /**
      * A listener using weak reference for notifying the enclosed image that a 
source changed.
      */
-    private static final class Listener extends WeakReference<MonolithicImage> 
implements TileObserver {
+    private static final class Listener extends WeakReference<MonolithicImage> 
implements PlanarImage.Observer {
         /**
          * Creates a new listener which will notify the given image.
          *
@@ -95,19 +116,17 @@ abstract class MonolithicImage extends PlanarImage {
          * Invoked when a source image changed.
          * The enclosed image is notified only after the tile calculation 
finished.
          *
-         * @param source  the image that owns the updated tile.
-         * @param tileX   the <var>x</var> index of the tile that is being 
updated.
-         * @param tileY   the <var>y</var> index of the tile that is being 
updated.
-         * @param willBeWritable  {@code true} before writing, {@code false} 
after released.
+         * @param source   the image that owns the updated tile.
+         * @param tileX    the <var>x</var> index of the tile that is being 
updated.
+         * @param tileY    the <var>y</var> index of the tile that is being 
updated.
+         * @param writing  {@code true} before writing, {@code false} after 
update.
          */
         @Override
-        public void tileUpdate(final WritableRenderedImage source, final int 
tileX, final int tileY,
-                               final boolean willBeWritable)
-        {
+        public void tileUpdate(final RenderedImage source, final int tileX, 
final int tileY, final boolean writing) {
             final MonolithicImage target = get();
             if (target == null) {
-                source.removeTileObserver(this);
-            } else if (willBeWritable) {
+                removeTileObserver(source, this);
+            } else if (writing) {
                 /*
                  * Wait for completion before to mark source tile as updated. 
We should also ensure
                  * that the tile is not used before completion, but this is 
not yet implemented.
@@ -128,4 +147,43 @@ abstract class MonolithicImage extends PlanarImage {
      * @see ComputedImage#sourceTileChanged(RenderedImage, int, int)
      */
     protected abstract void sourceTileChanged(RenderedImage source, int tileX, 
int tileY);
+
+    /**
+     * Adds an observer to be notified when a tile is about to be modified.
+     * A tile can be modified indirectly if one of the source images changed.
+     * The given listener should be an instance of {@link Observer} in order
+     * to be notified even if this image is not a {@link 
WritableRenderedImage}.
+     *
+     * @param  observer  the observer to notify, ignored if {@code null}.
+     *         If already present, it will receive multiple notifications.
+     */
+    @Override
+    public synchronized void addTileObserver(final TileObserver observer) {
+        if (observer instanceof Observer || this instanceof 
WritableRenderedImage) {
+            observers = WritableUntiledImage.addTileObserver(observers, 
observer);
+        }
+    }
+
+    /**
+     * Removes an observer from the list of observers notified when a tile is 
modified.
+     * If the observer was not registered, nothing happens.
+     * If the observer was registered for multiple notifications, it will now 
be registered for one fewer.
+     *
+     * @param  observer  the observer to stop notifying.
+     */
+    @Override
+    public synchronized void removeTileObserver(final TileObserver observer) {
+        observers = WritableUntiledImage.removeTileObserver(observers, 
observer);
+    }
+
+    /**
+     * Notifies listeners that a tile is about to be modified or has been 
modified.
+     *
+     * @param  tileX    the <var>x</var> index of the tile to acquire or 
release.
+     * @param  tileY    the <var>y</var> index of the tile to acquire or 
release.
+     * @param  writing  {@code true} if the tile will be modified, or {@code 
false} if the modification is done.
+     */
+    final void fireTileUpdate(final int tileX, final int tileY, final boolean 
writing) {
+        fireTileUpdate(observers, this, tileX, tileY, writing);
+    }
 }
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PlanarImage.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PlanarImage.java
index 6ae7d6e5f8..3cfd5f477f 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PlanarImage.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PlanarImage.java
@@ -26,6 +26,7 @@ import java.awt.image.WritableRaster;
 import java.awt.image.WritableRenderedImage;
 import java.awt.image.RenderedImage;
 import java.awt.image.ImagingOpException;
+import java.awt.image.TileObserver;
 import java.util.Objects;
 import java.util.Vector;
 import java.util.function.DoubleUnaryOperator;
@@ -83,7 +84,7 @@ import org.apache.sis.pending.jdk.JDK18;
  * {@link #getData(Rectangle)} and {@link #copyData(WritableRaster)}
  * in terms of above methods.
  *
- * <h2>Writable images</h2>
+ * <h2>Writing in a planar image</h2>
  * Some subclasses may implement the {@link WritableRenderedImage} interface. 
If this image is writable,
  * then the {@link WritableRenderedImage#getWritableTile 
WritableRenderedImage.getWritableTile(…)} and
  * {@link WritableRenderedImage#releaseWritableTile releaseWritableTile(…)} 
methods should be invoked in
@@ -100,7 +101,7 @@ import org.apache.sis.pending.jdk.JDK18;
  *     }
  *
  * This is recommended because implementations may count the number of 
acquisitions and releases for deciding
- * when to notify the {@link java.awt.image.TileObserver}s. Some 
implementations may also acquire and release
+ * when to notify the {@linkplain TileObserver tile observers}. Some 
implementations may also acquire and release
  * synchronization locks in the {@code getWritableTile(…)} and {@code 
releaseWritableTile(…)} methods.
  * Apache SIS <a href="https://issues.apache.org/jira/browse/SIS-487";>does not 
yet define a synchronization policy</a>
  * for {@link WritableRenderedImage}, but such policy may be defined in a 
future version.
@@ -674,6 +675,152 @@ public abstract class PlanarImage implements 
RenderedImage {
         return null;
     }
 
+    /**
+     * Adds an observer to be notified when a tile is about to be modified.
+     * A tile can be modified directly if this image implements the {@link 
WritableRenderedImage} interface
+     * and a tile has been acquired for writing, or indirectly if this image 
is computed from other sources
+     * and one of the source images changed. In the latter case, the given 
listener should be an instance of
+     * {@link Observer} in order to be notified even if this image is not a 
{@link WritableRenderedImage}.
+     *
+     * <p>The default implementation does nothing. This method is overridden 
by subclasses
+     * such as {@link ComputedImage}, {@link AggregatedImage} and all writable 
images.</p>
+     *
+     * @param  observer  the observer to notify, ignored if {@code null}.
+     *         If already present, it will receive multiple notifications.
+     *
+     * @see WritableRenderedImage#addTileObserver(TileObserver)
+     * @see Observer
+     *
+     * @since SIS 1.8
+     */
+    public void addTileObserver(TileObserver observer) {
+    }
+
+    /**
+     * Removes an observer from the list of observers notified when a tile is 
modified.
+     * If the observer was not registered, nothing happens.
+     * If the observer was registered for multiple notifications, it will now 
be registered for one fewer.
+     *
+     * <p>The default implementation does nothing. This method is overridden 
by subclasses
+     * such as {@link ComputedImage}, {@link AggregatedImage} and all writable 
images.</p>
+     *
+     * @param  observer  the observer to stop notifying. Ignored if {@code 
null} or absent.
+     *
+     * @see WritableRenderedImage#removeTileObserver(TileObserver)
+     *
+     * @since SIS 1.8
+     */
+    public void removeTileObserver(TileObserver observer) {
+    }
+
+    /**
+     * Adds an observer to the given image if possible.
+     *
+     * @param  image     the image on which to add an observer.
+     * @param  observer  the observer to add.
+     * @return whether a listener has been added.
+     */
+    static boolean addTileObserver(final RenderedImage image, final 
TileObserver observer) {
+        if (image instanceof PlanarImage) {
+            ((PlanarImage) image).addTileObserver(observer);
+        } else if (image instanceof WritableRenderedImage) {
+            ((WritableRenderedImage) image).addTileObserver(observer);
+        } else {
+            return false;
+        }
+        return false;
+    }
+
+    /**
+     * Removes an observer from the given image if present.
+     *
+     * @param  image     the image from which to remove an observer.
+     * @param  observer  the observer to add.
+     */
+    static void removeTileObserver(final RenderedImage image, final 
TileObserver observer) {
+        if (image instanceof PlanarImage) {
+            ((PlanarImage) image).removeTileObserver(observer);
+        } else if (image instanceof WritableRenderedImage) {
+            ((WritableRenderedImage) image).removeTileObserver(observer);
+        }
+    }
+
+    /**
+     * Notifies all listeners that the specified tile is about to change or 
has changed.
+     *
+     * @param observers  the observers to notify, or {@code null} if none.
+     * @param image      the image that owns the tile.
+     * @param tileX      the <var>x</var> index of the modified tile.
+     * @param tileY      the <var>y</var> index of the modified tile.
+     * @param writing    {@code true} if the tile will be modified, or {@code 
false} if the modification is done.
+     */
+    static void fireTileUpdate(final TileObserver[] observers, final 
RenderedImage image,
+                               final int tileX, final int tileY, final boolean 
writing)
+    {
+        if (observers != null) {
+            if (image instanceof WritableRenderedImage) {
+                final var writable = (WritableRenderedImage) image;
+                for (final TileObserver observer : observers) {
+                    observer.tileUpdate(writable, tileX, tileY, writing);
+                }
+            } else {
+                for (final TileObserver observer : observers) {
+                    if (observer instanceof Observer) {
+                        ((Observer) observer).tileUpdate(image, tileX, tileY, 
writing);
+                    }
+                }
+            }
+        }
+    }
+
+    /**
+     * An interface for objects that wish to be informed when an image is 
about to change or has changed.
+     * This is an extension of {@link TileObserver} where the modified image 
is not necessarily writable.
+     * The image can also be a {@linkplain ComputedImage computed image} when 
one of its sources changed.
+     *
+     * <p>When a change occurs, only one of the following methods will be 
invoked:</p>
+     * <ul>
+     *   <li>{@link #tileUpdate(WritableRenderedImage, int, int, boolean) 
tileUpdate(WritableRenderedImage, …)}
+     *       if the image that owns the modified tile is writable.</li>
+     *   <li>{@link #tileUpdate(RenderedImage, int, int, boolean) 
tileUpdate(RenderedImage, …)} otherwise.</li>
+     * </ul>
+     *
+     * Because the default implementation of the former delegates to the 
latter,
+     * it is okay to implement only the latter.
+     *
+     * @author  Martin Desruisseaux (Geomatys)
+     * @version 1.8
+     *
+     * @since SIS 1.8
+     */
+    public interface Observer extends TileObserver {
+        /**
+         * Invoked when a tile has been checked out for writing or has been 
released.
+         * The default implementation delegates to
+         * {@link #tileUpdate(RenderedImage, int, int, boolean) 
tileUpdate(RenderedImage, …)}.
+         *
+         * @param image  the writable image that owns the modified tile.
+         * @param tileX  the <var>x</var> index of the tile to acquire or 
release.
+         * @param tileY  the <var>y</var> index of the tile to acquire or 
release.
+         * @param willBeWritable {@code true} if the tile will be grabbed for 
writing,
+         *        or {@code false} if the tile is being released.
+         */
+        @Override
+        default void tileUpdate(WritableRenderedImage image, int tileX, int 
tileY, boolean willBeWritable) {
+            tileUpdate((RenderedImage) image, tileX, tileY, willBeWritable);
+        }
+
+        /**
+         * Invoked when a tile is about to be updated, and after the update is 
done.
+         *
+         * @param image    the image that owns the modified tile.
+         * @param tileX    the <var>x</var> index of the modified tile.
+         * @param tileY    the <var>y</var> index of the modified tile.
+         * @param writing  {@code true} if the tile will be modified, or 
{@code false} if the modification is done.
+         */
+        void tileUpdate(RenderedImage image, int tileX, int tileY, boolean 
writing);
+    }
+
     /**
      * Ensures that a user supplied color model is compatible with the sample 
model.
      * This is a helper method for argument validation in sub-classes 
constructors.
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/WritableComputedImage.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/WritableComputedImage.java
index a689c83d00..8243ff12b7 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/WritableComputedImage.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/WritableComputedImage.java
@@ -17,12 +17,10 @@
 package org.apache.sis.image;
 
 import java.awt.image.SampleModel;
-import java.awt.image.TileObserver;
 import java.awt.image.Raster;
 import java.awt.image.RenderedImage;
 import java.awt.image.WritableRaster;
 import java.awt.image.WritableRenderedImage;
-import org.apache.sis.image.internal.shared.WritableUntiledImage;
 
 
 /**
@@ -72,17 +70,6 @@ import 
org.apache.sis.image.internal.shared.WritableUntiledImage;
  * @author  Martin Desruisseaux (Geomatys)
  */
 abstract class WritableComputedImage extends ComputedImage {
-    /**
-     * The observers, or {@code null} if none. This is a copy-on-write array:
-     * values are never modified after construction (new arrays are created).
-     *
-     * This field is declared volatile because it is read without 
synchronization by
-     * {@link #markTileWritable(int, int, boolean)}. Since this is a 
copy-on-write array,
-     * it is okay to omit synchronization for that method but we still need 
the memory effect.
-     */
-    @SuppressWarnings("VolatileArrayField")
-    private volatile TileObserver[] observers;
-
     /**
      * Creates an initially empty image with the given sample model.
      * The source images are not necessarily {@link WritableRenderedImage}
@@ -97,43 +84,6 @@ abstract class WritableComputedImage extends ComputedImage {
         super(sampleModel, sources);
     }
 
-    /**
-     * Adds an observer to be notified when a tile is checked out for writing.
-     * If the observer is already present, it will receive multiple 
notifications.
-     *
-     * @param  observer  the observer to notify.
-     */
-    public synchronized void addTileObserver(final TileObserver observer) {
-        observers = WritableUntiledImage.addTileObserver(observers, observer);
-    }
-
-    /**
-     * Removes an observer from the list of observers notified when a tile is 
checked out for writing.
-     * If the observer was not registered, nothing happens. If the observer 
was registered for multiple
-     * notifications, it will now be registered for one fewer.
-     *
-     * @param  observer  the observer to stop notifying.
-     */
-    public synchronized void removeTileObserver(final TileObserver observer) {
-        observers = WritableUntiledImage.removeTileObserver(observers, 
observer);
-    }
-
-    /**
-     * Sets or clears whether a tile is checked out for writing and notifies 
the listener if needed.
-     *
-     * @param  tileX    the <var>x</var> index of the tile to acquire or 
release.
-     * @param  tileY    the <var>y</var> index of the tile to acquire or 
release.
-     * @param  writing  {@code true} for acquiring the tile, or {@code false} 
for releasing it.
-     */
-    @Override
-    protected boolean markTileWritable(final int tileX, final int tileY, final 
boolean writing) {
-        final boolean notify = super.markTileWritable(tileX, tileY, writing);
-        if (notify && this instanceof WritableRenderedImage) {
-            WritableUntiledImage.fireTileUpdate(observers, 
(WritableRenderedImage) this, tileX, tileY, writing);
-        }
-        return notify;
-    }
-
     /**
      * Checks out a tile for writing.
      *
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/FillValues.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/FillValues.java
index bdf467f389..f41c1d10bd 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/FillValues.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/FillValues.java
@@ -106,14 +106,27 @@ public final class FillValues {
         isFullyZero = (zeroFlag == 0);
     }
 
+    /**
+     * Returns the content of {@link #asPrimitiveArray} as an array of 
double-precision values.
+     * This method always returns copy, the backing array is never returned.
+     *
+     * @return the fill values as an array of double-precision values.
+     */
+    public double[] asDoubles() {
+        final var values = new double[Array.getLength(asPrimitiveArray)];
+        Arrays.fill(values, Double.NaN);
+        Arrays.setAll(values, (i) -> Array.getDouble(asPrimitiveArray, i));
+        return values;
+    }
+
     /**
      * Fills the given raster with the fill value. The raster sample model 
should be the same
      * than the sample model specified at construction time of this {@code 
FillValues} object.
      *
-     * <h4>Implementation note</h4>
+     * <p><b>Implementation note</b>
      * This method fills the raster using its API, without direct access to 
the backing array.
      * We do not use direct array access because it would disable Java2D 
hardware acceleration
-     * in subsequent operations.
+     * in subsequent operations.</p>
      *
      * @param  tile  the raster to fill.
      *
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/WritableTiledImage.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/WritableTiledImage.java
index da3800ab6b..986da20ea1 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/WritableTiledImage.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/WritableTiledImage.java
@@ -139,13 +139,24 @@ public class WritableTiledImage extends TiledImage 
implements WritableRenderedIm
             if (tile == null) {
                 final int x = ImageUtilities.tileToPixelX(this, tileX);
                 final int y = ImageUtilities.tileToPixelY(this, tileY);
-                tile = WritableRaster.createWritableRaster(sampleModel, new 
Point(x, y));
-                tiles[index] = tile;
+                tiles[index] = tile = createTile(new Point(x, y));
             }
             return tile;
         }
     }
 
+    /**
+     * Creates an initially empty tile. This method is invoked when {@link 
#getTile(int, int)}
+     * is requested for a tile that does not exist yet. Subclasses can 
override this method in
+     * order, for example, to fill the new tile with a fill value.
+     *
+     * @param  location  the upper-left corner of the tile.
+     * @return a new raster for a tile at the given location.
+     */
+    protected WritableRaster createTile(final Point location) {
+        return WritableRaster.createWritableRaster(sampleModel, location);
+    }
+
     /**
      * Checks out a tile for writing. If the same tile is checked out many 
times
      * before to be released, only the first checkout is notified to listeners.
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/WritableUntiledImage.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/WritableUntiledImage.java
index bde63bfe6f..abeeb4c0bb 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/WritableUntiledImage.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/WritableUntiledImage.java
@@ -260,8 +260,8 @@ public final class WritableUntiledImage extends 
BufferedImage {
      * @param tileY           the <var>y</var> index of the tile that is being 
updated.
      * @param willBeWritable  if {@code true}, the tile will be grabbed for 
writing; otherwise it is being released.
      */
-    public static void fireTileUpdate(final TileObserver[] observers, final 
WritableRenderedImage image,
-                                      final int tileX, final int tileY, final 
boolean willBeWritable)
+    static void fireTileUpdate(final TileObserver[] observers, final 
WritableRenderedImage image,
+                               final int tileX, final int tileY, final boolean 
willBeWritable)
     {
         if (observers != null) {
             for (final TileObserver observer : observers) {
diff --git 
a/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/AggregatedImageTest.java
 
b/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/AggregatedImageTest.java
index 4154815c68..6ba67ab4ae 100644
--- 
a/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/AggregatedImageTest.java
+++ 
b/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/AggregatedImageTest.java
@@ -16,11 +16,14 @@
  */
 package org.apache.sis.image;
 
+import java.util.Map;
+import java.util.HashMap;
 import java.awt.Point;
 import java.awt.Dimension;
 import java.awt.Rectangle;
 import java.awt.image.DataBuffer;
 import java.awt.image.Raster;
+import java.awt.image.RenderedImage;
 import java.awt.image.WritableRaster;
 import org.opengis.referencing.operation.TransformException;
 import org.apache.sis.image.internal.shared.WritableTiledImage;
@@ -50,7 +53,7 @@ import org.apache.sis.test.TestCase;
  * @author  Martin Desruisseaux (Geomatys)
  */
 @SuppressWarnings("exports")
-public final class AggregatedImageTest extends TestCase {
+public final class AggregatedImageTest extends TestCase implements 
PlanarImage.Observer {
     /**
      * The image bounds, or {@code null} for automatic.
      * Used at construction and for verifying the properties of the result.
@@ -86,10 +89,43 @@ public final class AggregatedImageTest extends TestCase {
      */
     private boolean parallel;
 
+    /**
+     * Indexes of tiles which are updated. Keys are the last value of the 
{@code writing} argument
+     * in the call to {@link #tileUpdate(java.awt.image.RenderedImage, int, 
int, boolean)} method.
+     */
+    private final Map<Point, Boolean> updatedTiles;
+
     /**
      * Creates a new test case.
      */
     public AggregatedImageTest() {
+        updatedTiles = new HashMap<>();
+    }
+
+    /**
+     * Invoked when a tile is about to be updated or has been updated.
+     * This method asserts that for each tile, the method is invoked once
+     * with {@code writing} equals to {@code true} then once with {@code 
false}.
+     */
+    @Override
+    public void tileUpdate(final RenderedImage image, final int tileX, final 
int tileY, final boolean writing) {
+        final Boolean previous = updatedTiles.put(new Point(tileX, tileY), 
writing);
+        if (writing) {
+            assertNull(previous);
+        } else {
+            assertEquals(Boolean.TRUE, previous);
+        }
+    }
+
+    /**
+     * Asserts that the file at the given index has been updated.
+     *
+     * @param tileX  the <var>x</var> index of the modified tile.
+     * @param tileY  the <var>y</var> index of the modified tile.
+     */
+    private void assertUpdatedTile(final int tileX, final int tileY) {
+        assertEquals(Boolean.FALSE, updatedTiles.remove(new Point(tileX, 
tileY)),
+                () -> "Tile (" + tileX + ", " + tileY + ')');
     }
 
     /**
@@ -142,6 +178,7 @@ public final class AggregatedImageTest extends TestCase {
         final var layout   = new ImageLayout(null, tileSize, false, false, 
true, minTile);
         image = new AggregatedImage(sources, layout, bounds, 
Aggregation.RASTER_SPACE_WEIGHTING, null);
         image.parallel = parallel;
+        image.addTileObserver(this);
     }
 
     /**
@@ -229,6 +266,9 @@ public final class AggregatedImageTest extends TestCase {
                 1105.5f, 1107.5f, 1205.5f, 1207.5f,
                 1210.5f, 1212.5f, 1310.5f, 1312.5f,
                 1315.5f, 1317.5f, 1415.5f, 1417.5f);
+
+        // Expect no tile update event.
+        assertTrue(updatedTiles.isEmpty());
     }
 
     /**
@@ -275,6 +315,9 @@ public final class AggregatedImageTest extends TestCase {
                 1311, 1312, 1855, 1856, 1906,       2401,     NaN,  NaN,  NaN, 
 NaN,
                  NaN,  NaN, 2310, 2311, 2410,       2411,     NaN,  NaN,  NaN, 
 NaN,
                  NaN,  NaN, 2320, 2321, 2420,       2421,     NaN,  NaN,  NaN, 
 NaN);
+
+        // Expect no tile update event.
+        assertTrue(updatedTiles.isEmpty());
     }
 
     /**
@@ -349,6 +392,9 @@ public final class AggregatedImageTest extends TestCase {
                 NaN, NaN, 5100.5f, 5200.5f, 5300.5f,
                 NaN, NaN, 5110.5f, 5210.5f, 5310.5f,
                 NaN, NaN, 5120.5f, 5220.5f, 5320.5f);
+
+        // Expect no tile update event.
+        assertTrue(updatedTiles.isEmpty());
     }
 
     /**
@@ -360,6 +406,16 @@ public final class AggregatedImageTest extends TestCase {
      */
     @Test
     public void testRecompute() throws TransformException {
+        testRecompute(true);
+    }
+
+    /**
+     * Implementation of {@link #testRecompute()} and {@link 
#testRecomputeOnlyDirtyTiles()}.
+     *
+     * @param  twoChanges  {@code true} for updating two tiles, or {@code 
false} for updating only one time.
+     * @throws TransformException if an error occurred while computing the 
bounds of the aggregated image.
+     */
+    private void testRecompute(final boolean twoChanges) throws 
TransformException {
         tileWidth  =  5;
         tileHeight =  3;
         minTileX   =  4;
@@ -376,21 +432,51 @@ public final class AggregatedImageTest extends TestCase {
                 1400, 1401, 1500, 1501, 1600, 1601,
                 1410, 1411, 1510, 1511, 1610, 1611);
         /*
-         * Modify the pixel at (10, -2) in the second tile and the pixel at 
(11, 0) in the sixth tile.
+         * Modify the pixel at (10, -2) in the second tile of the source image.
+         * This is the pixel at (1, 3) in the aggregated image, in tile (4, 
-1).
          * The tile observers are notified when the writable tiles are 
released.
          */
         WritableRaster tile = source.getWritableTile(-2, 2);
         tile.setSample(10, -2, 0, 5000);
         source.releaseWritableTile(-2, 2);
-
-        tile = source.getWritableTile(-1, 3);
-        tile.setSample(11, 0, 0, 6000);
-        source.releaseWritableTile(-1, 3);
-
+        /*
+         * Modify the pixel at (10, -2) in the second tile and the pixel at 
(11, 0) in the sixth tile.
+         * The tile observers are notified when the writable tiles are 
released.
+         */
+        float flag = 1610;
+        if (twoChanges) {
+            tile = source.getWritableTile(-1, 3);
+            tile.setSample(11, 0, 0, 6000);
+            source.releaseWritableTile(-1, 3);
+            flag = 6000;
+        }
         verify(0,   // Number of the band to verify
                 1100, 1101, 1200, 1201, 1300, 1301,
                 1110, 1111, 1210, 5000, 1310, 1311,
                 1400, 1401, 1500, 1501, 1600, 1601,
-                1410, 1411, 1510, 1511, 6000, 1611);
+                1410, 1411, 1510, 1511, flag, 1611);
+
+        assertFalse(updatedTiles.isEmpty());
+        assertUpdatedTile(4, -1);
+        if (twoChanges) {
+            assertUpdatedTile(4,  0);
+            assertUpdatedTile(5,  0);
+            assertUpdatedTile(5, -1);
+        }
+        assertTrue(updatedTiles.isEmpty());
+    }
+
+    /**
+     * Tests that only the tiles affected by a change in a source image are 
recomputed.
+     * This is the same setup as {@link #testRecompute()},
+     * but with a single modification in the source image.
+     * That modification affects only the upper-left tile of the aggregated 
image.
+     * Other tiles shall not be recomputed and shall keep their values.
+     *
+     * @throws TransformException if an error occurred while computing the 
bounds of the aggregated image.
+     */
+    @Test
+    public void testRecomputeOnlyDirtyTiles() throws TransformException {
+        testRecompute(false);
     }
 }
diff --git 
a/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/TiledImageMock.java
 
b/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/TiledImageMock.java
index 11083e2e9a..255935322e 100644
--- 
a/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/TiledImageMock.java
+++ 
b/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/TiledImageMock.java
@@ -36,7 +36,6 @@ import java.awt.image.PixelInterleavedSampleModel;
 import java.awt.image.Raster;
 import java.awt.image.RasterFormatException;
 import java.awt.image.SampleModel;
-import java.awt.image.TileObserver;
 import java.awt.image.WritableRaster;
 import java.awt.image.WritableRenderedImage;
 import org.apache.sis.image.internal.shared.ImageUtilities;
@@ -561,20 +560,6 @@ public final class TiledImageMock extends PlanarImage 
implements WritableRendere
         return isTileAcquired ? new Point[] {new Point(acquiredTileX, 
acquiredTileY)} : null;
     }
 
-    /**
-     * Ignored since we do not need tile observers for the tests.
-     */
-    @Override
-    public void addTileObserver(TileObserver to) {
-    }
-
-    /**
-     * Ignored since no listener can have been registered.
-     */
-    @Override
-    public void removeTileObserver(TileObserver to) {
-    }
-
     /**
      * Sets a rectangle of this image to the contents of given raster.
      * The raster is assumed to be in the same coordinate space as this image.

Reply via email to