GenericTimeStampedCache.java

  1. /* Copyright 2002-2013 CS Systèmes d'Information
  2.  * Licensed to CS Systèmes d'Information (CS) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * CS licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *   http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.orekit.utils;

  18. import java.lang.reflect.Array;
  19. import java.util.ArrayList;
  20. import java.util.Arrays;
  21. import java.util.List;
  22. import java.util.concurrent.atomic.AtomicInteger;
  23. import java.util.concurrent.atomic.AtomicLong;
  24. import java.util.concurrent.atomic.AtomicReference;
  25. import java.util.concurrent.locks.ReadWriteLock;
  26. import java.util.concurrent.locks.ReentrantReadWriteLock;

  27. import org.apache.commons.math3.exception.util.LocalizedFormats;
  28. import org.apache.commons.math3.util.FastMath;
  29. import org.orekit.errors.OrekitException;
  30. import org.orekit.errors.OrekitMessages;
  31. import org.orekit.errors.TimeStampedCacheException;
  32. import org.orekit.time.AbsoluteDate;
  33. import org.orekit.time.TimeStamped;

  34. /** Generic thread-safe cache for {@link TimeStamped time-stamped} data.

  35.  * @param <T> Type of the cached data.

  36.  * @author Luc Maisonobe
  37.  */
  38. public class GenericTimeStampedCache<T extends TimeStamped> implements TimeStampedCache<T> {

  39.     /** Default number of independent cached time slots. */
  40.     public static final int DEFAULT_CACHED_SLOTS_NUMBER = 10;

  41.     /** Quantum step. */
  42.     private static final double QUANTUM_STEP = 1.0e-6;

  43.     /** Reference date for indexing. */
  44.     private final AtomicReference<AbsoluteDate> reference;

  45.     /** Maximum number of independent cached time slots. */
  46.     private final int maxSlots;

  47.     /** Maximum duration span in seconds of one slot. */
  48.     private final double maxSpan;

  49.     /** Quantum gap above which a new slot is created instead of extending an existing one. */
  50.     private final long newSlotQuantumGap;

  51.     /** Class of the cached entries. */
  52.     private final Class<T> entriesClass;

  53.     /** Generator to use for yet non-cached data. */
  54.     private final TimeStampedGenerator<T> generator;

  55.     /** Number of entries in a neighbors array. */
  56.     private final int neighborsSize;

  57.     /** Independent time slots cached. */
  58.     private final List<Slot> slots;

  59.     /** Number of calls to the getNeighbors method. */
  60.     private final AtomicInteger getNeighborsCalls;

  61.     /** Number of calls to the generate method. */
  62.     private final AtomicInteger generateCalls;

  63.     /** Number of evictions. */
  64.     private final AtomicInteger evictions;

  65.     /** Global lock. */
  66.     private final ReadWriteLock lock;

  67.     /** Simple constructor.
  68.      * @param neighborsSize fixed size of the arrays to be returned by {@link
  69.      * #getNeighbors(AbsoluteDate)}, must be at least 2
  70.      * @param maxSlots maximum number of independent cached time slots
  71.      * @param maxSpan maximum duration span in seconds of one slot
  72.      * (can be set to {@code Double.POSITIVE_INFINITY} if desired)
  73.      * @param newSlotInterval time interval above which a new slot is created
  74.      * instead of extending an existing one
  75.      * @param generator generator to use for yet non-existent data
  76.      * @param entriesClass class of the cached entries
  77.      */
  78.     public GenericTimeStampedCache(final int neighborsSize, final int maxSlots, final double maxSpan,
  79.                                    final double newSlotInterval, final TimeStampedGenerator<T> generator,
  80.                                    final Class<T> entriesClass) {

  81.         // safety check
  82.         if (maxSlots < 1) {
  83.             throw OrekitException.createIllegalArgumentException(LocalizedFormats.NUMBER_TOO_SMALL, maxSlots, 1);
  84.         }
  85.         if (neighborsSize < 2) {
  86.             throw OrekitException.createIllegalArgumentException(OrekitMessages.NOT_ENOUGH_CACHED_NEIGHBORS,
  87.                                                                  neighborsSize, 2);
  88.         }

  89.         this.reference         = new AtomicReference<AbsoluteDate>();
  90.         this.maxSlots          = maxSlots;
  91.         this.maxSpan           = maxSpan;
  92.         this.newSlotQuantumGap = FastMath.round(newSlotInterval / QUANTUM_STEP);
  93.         this.entriesClass      = entriesClass;
  94.         this.generator         = generator;
  95.         this.neighborsSize     = neighborsSize;
  96.         this.slots             = new ArrayList<Slot>(maxSlots);
  97.         this.getNeighborsCalls = new AtomicInteger(0);
  98.         this.generateCalls     = new AtomicInteger(0);
  99.         this.evictions         = new AtomicInteger(0);
  100.         this.lock              = new ReentrantReadWriteLock();

  101.     }

  102.     /** Get the generator.
  103.      * @return generator
  104.      */
  105.     public TimeStampedGenerator<T> getGenerator() {
  106.         return generator;
  107.     }

  108.     /** Get the maximum number of independent cached time slots.
  109.      * @return maximum number of independent cached time slots
  110.      */
  111.     public int getMaxSlots() {
  112.         return maxSlots;
  113.     }

  114.     /** Get the maximum duration span in seconds of one slot.
  115.      * @return maximum duration span in seconds of one slot
  116.      */
  117.     public double getMaxSpan() {
  118.         return maxSpan;
  119.     }

  120.     /** Get quantum gap above which a new slot is created instead of extending an existing one.
  121.      * <p>
  122.      * The quantum gap is the {@code newSlotInterval} value provided at construction
  123.      * rounded to the nearest quantum step used internally by the cache.
  124.      * </p>
  125.      * @return quantum gap in seconds
  126.      */
  127.     public double getNewSlotQuantumGap() {
  128.         return newSlotQuantumGap * QUANTUM_STEP;
  129.     }

  130.     /** Get the number of calls to the {@link #getNeighbors(AbsoluteDate)} method.
  131.      * <p>
  132.      * This number of calls is used as a reference to interpret {@link #getGenerateCalls()}.
  133.      * </p>
  134.      * @return number of calls to the {@link #getNeighbors(AbsoluteDate)} method
  135.      * @see #getGenerateCalls()
  136.      */
  137.     public int getGetNeighborsCalls() {
  138.         return getNeighborsCalls.get();
  139.     }

  140.     /** Get the number of calls to the generate method.
  141.      * <p>
  142.      * This number of calls is related to the number of cache misses and may
  143.      * be used to tune the cache configuration. Each cache miss implies at
  144.      * least one call is performed, but may require several calls if the new
  145.      * date is far offset from the existing cache, depending on the number of
  146.      * elements and step between elements in the arrays returned by the generator.
  147.      * </p>
  148.      * @return number of calls to the generate method
  149.      * @see #getGetNeighborsCalls()
  150.      */
  151.     public int getGenerateCalls() {
  152.         return generateCalls.get();
  153.     }

  154.     /** Get the number of slots evictions.
  155.      * <p>
  156.      * This number should remain small when the max number of slots is sufficient
  157.      * with respect to the number of concurrent requests to the cache. If it
  158.      * increases too much, then the cache configuration is probably bad and cache
  159.      * does not really improve things (in this case, the {@link #getGenerateCalls()
  160.      * number of calls to the generate method} will probably increase too.
  161.      * </p>
  162.      * @return number of slots evictions
  163.      */
  164.     public int getSlotsEvictions() {
  165.         return evictions.get();
  166.     }

  167.     /** Get the number of slots in use.
  168.      * @return number of slots in use
  169.      */
  170.     public int getSlots() {

  171.         lock.readLock().lock();
  172.         try {
  173.             return slots.size();
  174.         } finally {
  175.             lock.readLock().unlock();
  176.         }

  177.     }

  178.     /** Get the total number of entries cached.
  179.      * @return total number of entries cached
  180.      */
  181.     public int getEntries() {

  182.         lock.readLock().lock();
  183.         try {
  184.             int entries = 0;
  185.             for (final Slot slot : slots) {
  186.                 entries += slot.getEntries();
  187.             }
  188.             return entries;
  189.         } finally {
  190.             lock.readLock().unlock();
  191.         }

  192.     }

  193.     /** Get the earliest cached entry.
  194.      * @return earliest cached entry
  195.      * @exception IllegalStateException if the cache has no slots at all
  196.      * @see #getSlots()
  197.      */
  198.     public T getEarliest() throws IllegalStateException {

  199.         lock.readLock().lock();
  200.         try {
  201.             if (slots.isEmpty()) {
  202.                 throw OrekitException.createIllegalStateException(OrekitMessages.NO_CACHED_ENTRIES);
  203.             }
  204.             return slots.get(0).getEarliest();
  205.         } finally {
  206.             lock.readLock().unlock();
  207.         }

  208.     }

  209.     /** Get the latest cached entry.
  210.      * @return latest cached entry
  211.      * @exception IllegalStateException if the cache has no slots at all
  212.      * @see #getSlots()
  213.      */
  214.     public T getLatest() throws IllegalStateException {

  215.         lock.readLock().lock();
  216.         try {
  217.             if (slots.isEmpty()) {
  218.                 throw OrekitException.createIllegalStateException(OrekitMessages.NO_CACHED_ENTRIES);
  219.             }
  220.             return slots.get(slots.size() - 1).getLatest();
  221.         } finally {
  222.             lock.readLock().unlock();
  223.         }

  224.     }

  225.     /** Get the fixed size of the arrays to be returned by {@link #getNeighbors(AbsoluteDate)}.
  226.      * @return size of the array
  227.      */
  228.     public int getNeighborsSize() {
  229.         return neighborsSize;
  230.     }

  231.     /** Get the entries surrounding a central date.
  232.      * <p>
  233.      * If the central date is well within covered range, the returned array
  234.      * will be balanced with half the points before central date and half the
  235.      * points after it (depending on n parity, of course). If the central date
  236.      * is near the generator range boundary, then the returned array will be
  237.      * unbalanced and will contain only the n earliest (or latest) generated
  238.      * (and cached) entries. A typical example of the later case is leap seconds
  239.      * cache, since the number of leap seconds cannot be arbitrarily increased.
  240.      * </p>
  241.      * @param central central date
  242.      * @return array of cached entries surrounding specified date (the size
  243.      * of the array is fixed to the one specified in the {@link
  244.      * #GenericTimeStampedCache(int, int, double, double, TimeStampedGenerator,
  245.      * Class) constructor})
  246.      * @exception TimeStampedCacheException if entries are not chronologically
  247.      * sorted or if new data cannot be generated
  248.      * @see #getEarliest()
  249.      * @see #getLatest()
  250.      */
  251.     public List<T> getNeighbors(final AbsoluteDate central) throws TimeStampedCacheException {

  252.         lock.readLock().lock();
  253.         try {
  254.             getNeighborsCalls.incrementAndGet();
  255.             final long dateQuantum = quantum(central);
  256.             return Arrays.asList(selectSlot(central, dateQuantum).getNeighbors(central, dateQuantum));
  257.         } finally {
  258.             lock.readLock().unlock();
  259.         }

  260.     }

  261.     /** Convert a date to a rough global quantum.
  262.      * <p>
  263.      * We own a global read lock while calling this method.
  264.      * </p>
  265.      * @param date date to convert
  266.      * @return quantum corresponding to the date
  267.      */
  268.     private long quantum(final AbsoluteDate date) {
  269.         reference.compareAndSet(null, date);
  270.         return FastMath.round(date.durationFrom(reference.get()) / QUANTUM_STEP);
  271.     }

  272.     /** Select a slot containing a date.
  273.      * <p>
  274.      * We own a global read lock while calling this method.
  275.      * </p>
  276.      * @param date target date
  277.      * @param dateQuantum global quantum of the date
  278.      * @return slot covering the date
  279.      * @exception TimeStampedCacheException if entries are not chronologically
  280.      * sorted or if new data cannot be generated
  281.      */
  282.     private Slot selectSlot(final AbsoluteDate date, final long dateQuantum)
  283.         throws TimeStampedCacheException {

  284.         Slot selected = null;

  285.         int index = slots.isEmpty() ? 0 : slotIndex(dateQuantum);
  286.         if (slots.isEmpty() ||
  287.             slots.get(index).getEarliestQuantum() > dateQuantum + newSlotQuantumGap ||
  288.             slots.get(index).getLatestQuantum()   < dateQuantum - newSlotQuantumGap) {
  289.             // no existing slot is suitable

  290.             // upgrade the read lock to a write lock so we can change the list of available slots
  291.             lock.readLock().unlock();
  292.             lock.writeLock().lock();

  293.             try {
  294.                 // check slots again as another thread may have changed
  295.                 // the list while we were waiting for the write lock
  296.                 index = slots.isEmpty() ? 0 : slotIndex(dateQuantum);
  297.                 if (slots.isEmpty() ||
  298.                     slots.get(index).getEarliestQuantum() > dateQuantum + newSlotQuantumGap ||
  299.                     slots.get(index).getLatestQuantum()   < dateQuantum - newSlotQuantumGap) {

  300.                     // we really need to create a new slot in the current thread
  301.                     // (no other threads have created it while we were waiting for the lock)
  302.                     if ((!slots.isEmpty()) &&
  303.                         slots.get(index).getLatestQuantum() < dateQuantum - newSlotQuantumGap) {
  304.                         ++index;
  305.                     }

  306.                     if (slots.size() >= maxSlots) {
  307.                         // we must prevent exceeding allowed max

  308.                         // select the oldest accessed slot for eviction
  309.                         int evict = 0;
  310.                         for (int i = 0; i < slots.size(); ++i) {
  311.                             if (slots.get(i).getLastAccess() < slots.get(evict).getLastAccess()) {
  312.                                 evict = i;
  313.                             }
  314.                         }

  315.                         // evict the selected slot
  316.                         evictions.incrementAndGet();
  317.                         slots.remove(evict);

  318.                         if (evict < index) {
  319.                             // adjust index of created slot as it was shifted by the eviction
  320.                             index--;
  321.                         }
  322.                     }

  323.                     slots.add(index, new Slot(date));

  324.                 }

  325.             } finally {
  326.                 // downgrade back to a read lock
  327.                 lock.readLock().lock();
  328.                 lock.writeLock().unlock();
  329.             }
  330.         }

  331.         selected = slots.get(index);


  332.         return selected;

  333.     }

  334.     /** Get the index of the slot in which a date could be cached.
  335.      * <p>
  336.      * We own a global read lock while calling this method.
  337.      * </p>
  338.      * @param dateQuantum quantum of the date to search for
  339.      * @return the slot in which the date could be cached
  340.      */
  341.     private int slotIndex(final long dateQuantum) {

  342.         int  iInf = 0;
  343.         final long qInf = slots.get(iInf).getEarliestQuantum();
  344.         int  iSup = slots.size() - 1;
  345.         final long qSup = slots.get(iSup).getLatestQuantum();
  346.         while (iSup - iInf > 0) {
  347.             final int iInterp = (int) ((iInf * (qSup - dateQuantum) + iSup * (dateQuantum - qInf)) / (qSup - qInf));
  348.             final int iMed    = FastMath.max(iInf, FastMath.min(iInterp, iSup));
  349.             final Slot slot   = slots.get(iMed);
  350.             if (dateQuantum < slot.getEarliestQuantum()) {
  351.                 iSup = iMed - 1;
  352.             } else if (dateQuantum > slot.getLatestQuantum()) {
  353.                 iInf = FastMath.min(iSup, iMed + 1);
  354.             } else {
  355.                 return iMed;
  356.             }
  357.         }

  358.         return iInf;

  359.     }

  360.     /** Time slot. */
  361.     private final class Slot {

  362.         /** Cached time-stamped entries. */
  363.         private final List<Entry> cache;

  364.         /** Earliest quantum. */
  365.         private AtomicLong earliestQuantum;

  366.         /** Latest quantum. */
  367.         private AtomicLong latestQuantum;

  368.         /** Index from a previous recent call. */
  369.         private AtomicInteger guessedIndex;

  370.         /** Last access time. */
  371.         private AtomicLong lastAccess;

  372.         /** Simple constructor.
  373.          * @param date central date for initial entries to insert in the slot
  374.          * @exception TimeStampedCacheException if entries are not chronologically
  375.          * sorted or if new data cannot be generated
  376.          */
  377.         public Slot(final AbsoluteDate date) throws TimeStampedCacheException {

  378.             // allocate cache
  379.             this.cache = new ArrayList<Entry>();

  380.             // set up first entries
  381.             AbsoluteDate generationDate = date;

  382.             generateCalls.incrementAndGet();
  383.             for (final T entry : generateAndCheck(null, generationDate)) {
  384.                 cache.add(new Entry(entry, quantum(entry.getDate())));
  385.             }
  386.             earliestQuantum = new AtomicLong(cache.get(0).getQuantum());
  387.             latestQuantum   = new AtomicLong(cache.get(cache.size() - 1).getQuantum());

  388.             while (cache.size() < neighborsSize) {
  389.                 // we need to generate more entries

  390.                 final T entry0 = cache.get(0).getData();
  391.                 final T entryN = cache.get(cache.size() - 1).getData();
  392.                 generateCalls.incrementAndGet();

  393.                 final T existing;
  394.                 if (entryN.getDate().durationFrom(date) <= date.durationFrom(entry0.getDate())) {
  395.                     // generate additional point at the end of the slot
  396.                     existing = entryN;
  397.                     generationDate = entryN.getDate().shiftedBy(getMeanStep() * (neighborsSize - cache.size()));
  398.                     appendAtEnd(generateAndCheck(existing, generationDate));
  399.                 } else {
  400.                     // generate additional point at the start of the slot
  401.                     existing = entry0;
  402.                     generationDate = entry0.getDate().shiftedBy(-getMeanStep() * (neighborsSize - cache.size()));
  403.                     insertAtStart(generateAndCheck(existing, generationDate));
  404.                 }

  405.             }

  406.             guessedIndex    = new AtomicInteger(cache.size() / 2);
  407.             lastAccess      = new AtomicLong(System.currentTimeMillis());

  408.         }

  409.         /** Get the earliest entry contained in the slot.
  410.          * @return earliest entry contained in the slot
  411.          */
  412.         public T getEarliest() {
  413.             return cache.get(0).getData();
  414.         }

  415.         /** Get the quantum of the earliest date contained in the slot.
  416.          * @return quantum of the earliest date contained in the slot
  417.          */
  418.         public long getEarliestQuantum() {
  419.             return earliestQuantum.get();
  420.         }

  421.         /** Get the latest entry contained in the slot.
  422.          * @return latest entry contained in the slot
  423.          */
  424.         public T getLatest() {
  425.             return cache.get(cache.size() - 1).getData();
  426.         }

  427.         /** Get the quantum of the latest date contained in the slot.
  428.          * @return quantum of the latest date contained in the slot
  429.          */
  430.         public long getLatestQuantum() {
  431.             return latestQuantum.get();
  432.         }

  433.         /** Get the number of entries contained din the slot.
  434.          * @return number of entries contained din the slot
  435.          */
  436.         public int getEntries() {
  437.             return cache.size();
  438.         }

  439.         /** Get the mean step between entries.
  440.          * @return mean step between entries (or an arbitrary non-null value
  441.          * if there are fewer than 2 entries)
  442.          */
  443.         private double getMeanStep() {
  444.             if (cache.size() < 2) {
  445.                 return 1.0;
  446.             } else {
  447.                 final AbsoluteDate t0 = cache.get(0).getData().getDate();
  448.                 final AbsoluteDate tn = cache.get(cache.size() - 1).getData().getDate();
  449.                 return tn.durationFrom(t0) / (cache.size() - 1);
  450.             }
  451.         }

  452.         /** Get last access time of slot.
  453.          * @return last known access time
  454.          */
  455.         public long getLastAccess() {
  456.             return lastAccess.get();
  457.         }

  458.         /** Get the entries surrounding a central date.
  459.          * <p>
  460.          * If the central date is well within covered slot, the returned array
  461.          * will be balanced with half the points before central date and half the
  462.          * points after it (depending on n parity, of course). If the central date
  463.          * is near slot boundary and the underlying {@link TimeStampedGenerator
  464.          * generator} cannot extend it (i.e. it returns null), then the returned
  465.          * array will be unbalanced and will contain only the n earliest (or latest)
  466.          * cached entries. A typical example of the later case is leap seconds cache,
  467.          * since the number of leap seconds cannot be arbitrarily increased.
  468.          * </p>
  469.          * @param central central date
  470.          * @param dateQuantum global quantum of the date
  471.          * @return a new array containing date neighbors
  472.          * @exception TimeStampedCacheException if entries are not chronologically
  473.          * sorted or if new data cannot be generated
  474.          * @see #getBefore(AbsoluteDate)
  475.          * @see #getAfter(AbsoluteDate)
  476.          */
  477.         public T[] getNeighbors(final AbsoluteDate central, final long dateQuantum)
  478.             throws TimeStampedCacheException {

  479.             int index         = entryIndex(central, dateQuantum);
  480.             int firstNeighbor = index - (neighborsSize - 1) / 2;

  481.             if (firstNeighbor < 0 || firstNeighbor + neighborsSize > cache.size()) {
  482.                 // the cache is not balanced around the desired date, we can try to generate new data

  483.                 // upgrade the read lock to a write lock so we can change the list of available slots
  484.                 lock.readLock().unlock();
  485.                 lock.writeLock().lock();

  486.                 try {
  487.                     // check entries again as another thread may have changed
  488.                     // the list while we were waiting for the write lock
  489.                     boolean loop = true;
  490.                     while (loop) {
  491.                         index         = entryIndex(central, dateQuantum);
  492.                         firstNeighbor = index - (neighborsSize - 1) / 2;
  493.                         if (firstNeighbor < 0 || firstNeighbor + neighborsSize > cache.size()) {

  494.                             // estimate which data we need to be generated
  495.                             final double step = getMeanStep();
  496.                             final T existing;
  497.                             final AbsoluteDate generationDate;
  498.                             final boolean simplyRebalance;
  499.                             if (firstNeighbor < 0) {
  500.                                 existing        = cache.get(0).getData();
  501.                                 generationDate  = existing.getDate().shiftedBy(step * firstNeighbor);
  502.                                 simplyRebalance = existing.getDate().compareTo(central) <= 0;
  503.                             } else {
  504.                                 existing        = cache.get(cache.size() - 1).getData();
  505.                                 generationDate  = existing.getDate().shiftedBy(step * (firstNeighbor + neighborsSize - cache.size()));
  506.                                 simplyRebalance = existing.getDate().compareTo(central) >= 0;
  507.                             }
  508.                             generateCalls.incrementAndGet();

  509.                             // generated data and add it to the slot
  510.                             try {
  511.                                 if (firstNeighbor < 0) {
  512.                                     insertAtStart(generateAndCheck(existing, generationDate));
  513.                                 } else {
  514.                                     appendAtEnd(generateAndCheck(existing, generationDate));
  515.                                 }
  516.                             } catch (TimeStampedCacheException tce) {
  517.                                 if (simplyRebalance) {
  518.                                     // we were simply trying to rebalance an unbalanced interval near slot end
  519.                                     // we failed, but the central date is already covered by the existing (unbalanced) data
  520.                                     // so we ignore the exception and stop the loop, we will continue with what we have
  521.                                     loop = false;
  522.                                 } else {
  523.                                     throw tce;
  524.                                 }
  525.                             }

  526.                         } else {
  527.                             loop = false;
  528.                         }
  529.                     }
  530.                 } finally {
  531.                     // downgrade back to a read lock
  532.                     lock.readLock().lock();
  533.                     lock.writeLock().unlock();
  534.                 }

  535.             }

  536.             @SuppressWarnings("unchecked")
  537.             final T[] array = (T[]) Array.newInstance(entriesClass, neighborsSize);
  538.             if (firstNeighbor + neighborsSize > cache.size()) {
  539.                 // we end up with a non-balanced neighborhood,
  540.                 // adjust the start point to fit within the cache
  541.                 firstNeighbor = cache.size() - neighborsSize;
  542.             }
  543.             if (firstNeighbor < 0) {
  544.                 firstNeighbor = 0;
  545.             }
  546.             for (int i = 0; i < neighborsSize; ++i) {
  547.                 array[i] = cache.get(firstNeighbor + i).getData();
  548.             }

  549.             return array;

  550.         }

  551.         /** Get the index of the entry corresponding to a date.
  552.          * <p>
  553.          * We own a local read lock while calling this method.
  554.          * </p>
  555.          * @param date date
  556.          * @param dateQuantum global quantum of the date
  557.          * @return index in the array such that entry[index] is before
  558.          * date and entry[index + 1] is after date (or they are at array boundaries)
  559.          */
  560.         private int entryIndex(final AbsoluteDate date, final long dateQuantum) {

  561.             // first quick guesses, assuming a recent search was close enough
  562.             final int guess = guessedIndex.get();
  563.             if (guess > 0 && guess < cache.size()) {
  564.                 if (cache.get(guess).getQuantum() <= dateQuantum) {
  565.                     if (guess + 1 < cache.size() && cache.get(guess + 1).getQuantum() > dateQuantum) {
  566.                         // good guess!
  567.                         return guess;
  568.                     } else {
  569.                         // perhaps we have simply shifted just one point forward ?
  570.                         if (guess + 2 < cache.size() && cache.get(guess + 2).getQuantum() > dateQuantum) {
  571.                             guessedIndex.set(guess + 1);
  572.                             return guess + 1;
  573.                         }
  574.                     }
  575.                 } else {
  576.                     // perhaps we have simply shifted just one point backward ?
  577.                     if (guess > 1 && cache.get(guess - 1).getQuantum() <= dateQuantum) {
  578.                         guessedIndex.set(guess - 1);
  579.                         return guess - 1;
  580.                     }
  581.                 }
  582.             }

  583.             // quick guesses have failed, we need to perform a full blown search
  584.             if (dateQuantum < getEarliestQuantum()) {
  585.                 // date if before the first entry
  586.                 return -1;
  587.             } else if (dateQuantum > getLatestQuantum()) {
  588.                 // date is after the last entry
  589.                 return cache.size();
  590.             } else {

  591.                 // try to get an existing entry
  592.                 int  iInf = 0;
  593.                 final long qInf = cache.get(iInf).getQuantum();
  594.                 int  iSup = cache.size() - 1;
  595.                 final long qSup = cache.get(iSup).getQuantum();
  596.                 while (iSup - iInf > 0) {
  597.                     // within a continuous slot, entries are expected to be roughly linear
  598.                     final int iInterp = (int) ((iInf * (qSup - dateQuantum) + iSup * (dateQuantum - qInf)) / (qSup - qInf));
  599.                     final int iMed    = FastMath.max(iInf + 1, FastMath.min(iInterp, iSup));
  600.                     final Entry entry = cache.get(iMed);
  601.                     if (dateQuantum < entry.getQuantum()) {
  602.                         iSup = iMed - 1;
  603.                     } else if (dateQuantum > entry.getQuantum()) {
  604.                         iInf = iMed;
  605.                     } else {
  606.                         guessedIndex.set(iMed);
  607.                         return iMed;
  608.                     }
  609.                 }

  610.                 guessedIndex.set(iInf);
  611.                 return iInf;

  612.             }

  613.         }

  614.         /** Insert data at slot start.
  615.          * @param data data to insert
  616.          * @exception TimeStampedCacheException if new data cannot be generated
  617.          */
  618.         private void insertAtStart(final List<T> data) throws TimeStampedCacheException {

  619.             // insert data at start
  620.             boolean inserted = false;
  621.             final long q0 = earliestQuantum.get();
  622.             for (int i = 0; i < data.size(); ++i) {
  623.                 final long quantum = quantum(data.get(i).getDate());
  624.                 if (quantum < q0) {
  625.                     cache.add(i, new Entry(data.get(i), quantum));
  626.                     inserted = true;
  627.                 } else {
  628.                     break;
  629.                 }
  630.             }

  631.             if (!inserted) {
  632.                 throw new TimeStampedCacheException(OrekitMessages.UNABLE_TO_GENERATE_NEW_DATA_BEFORE,
  633.                                                               cache.get(0).getData().getDate());
  634.             }

  635.             // evict excess data at end
  636.             final AbsoluteDate t0 = cache.get(0).getData().getDate();
  637.             while (cache.size() > neighborsSize &&
  638.                    cache.get(cache.size() - 1).getData().getDate().durationFrom(t0) > maxSpan) {
  639.                 cache.remove(cache.size() - 1);
  640.             }

  641.             // update boundaries
  642.             earliestQuantum.set(cache.get(0).getQuantum());
  643.             latestQuantum.set(cache.get(cache.size() - 1).getQuantum());

  644.         }

  645.         /** Append data at slot end.
  646.          * @param data data to append
  647.          * @exception TimeStampedCacheException if new data cannot be generated
  648.          */
  649.         private void appendAtEnd(final List<T> data) throws TimeStampedCacheException {

  650.             // append data at end
  651.             boolean appended = false;
  652.             final long qn = latestQuantum.get();
  653.             final int  n  = cache.size();
  654.             for (int i = data.size() - 1; i >= 0; --i) {
  655.                 final long quantum = quantum(data.get(i).getDate());
  656.                 if (quantum > qn) {
  657.                     cache.add(n, new Entry(data.get(i), quantum));
  658.                     appended = true;
  659.                 } else {
  660.                     break;
  661.                 }
  662.             }

  663.             if (!appended) {
  664.                 throw new TimeStampedCacheException(OrekitMessages.UNABLE_TO_GENERATE_NEW_DATA_AFTER,
  665.                                                               cache.get(cache.size() - 1).getData().getDate());
  666.             }

  667.             // evict excess data at start
  668.             final AbsoluteDate tn = cache.get(cache.size() - 1).getData().getDate();
  669.             while (cache.size() > neighborsSize &&
  670.                    tn.durationFrom(cache.get(0).getData().getDate()) > maxSpan) {
  671.                 cache.remove(0);
  672.             }

  673.             // update boundaries
  674.             earliestQuantum.set(cache.get(0).getQuantum());
  675.             latestQuantum.set(cache.get(cache.size() - 1).getQuantum());

  676.         }

  677.         /** Generate entries and check ordering.
  678.          * @param existing closest already existing entry (may be null)
  679.          * @param date date that must be covered by the range of the generated array
  680.          * (guaranteed to lie between {@link #getEarliest()} and {@link #getLatest()})
  681.          * @return chronologically sorted list of generated entries
  682.          * @exception TimeStampedCacheException if if entries are not chronologically
  683.          * sorted or if new data cannot be generated
  684.          */
  685.         private List<T> generateAndCheck(final T existing, final AbsoluteDate date)
  686.             throws TimeStampedCacheException {
  687.             final List<T> entries = generator.generate(existing, date);
  688.             if (entries.isEmpty()) {
  689.                 throw new TimeStampedCacheException(OrekitMessages.NO_DATA_GENERATED, date);
  690.             }
  691.             for (int i = 1; i < entries.size(); ++i) {
  692.                 if (entries.get(i).getDate().compareTo(entries.get(i - 1).getDate()) < 0) {
  693.                     throw new TimeStampedCacheException(OrekitMessages.NON_CHRONOLOGICALLY_SORTED_ENTRIES,
  694.                                                                   entries.get(i - 1).getDate(),
  695.                                                                   entries.get(i).getDate());
  696.                 }
  697.             }
  698.             return entries;
  699.         }

  700.         /** Container for entries. */
  701.         private class Entry {

  702.             /** Entry data. */
  703.             private final T data;

  704.             /** Global quantum of the entry. */
  705.             private final long quantum;

  706.             /** Simple constructor.
  707.              * @param data entry data
  708.              * @param quantum entry quantum
  709.              */
  710.             public Entry(final T data, final long quantum) {
  711.                 this.quantum = quantum;
  712.                 this.data  = data;
  713.             }

  714.             /** Get the quantum.
  715.              * @return quantum
  716.              */
  717.             public long getQuantum() {
  718.                 return quantum;
  719.             }

  720.             /** Get the data.
  721.              * @return data
  722.              */
  723.             public T getData() {
  724.                 return data;
  725.             }

  726.         }
  727.     }

  728. }