GenericTimeStampedCache.java

  1. /* Copyright 2002-2018 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.util.ArrayList;
  19. import java.util.List;
  20. import java.util.concurrent.atomic.AtomicInteger;
  21. import java.util.concurrent.atomic.AtomicLong;
  22. import java.util.concurrent.atomic.AtomicReference;
  23. import java.util.concurrent.locks.ReadWriteLock;
  24. import java.util.concurrent.locks.ReentrantReadWriteLock;
  25. import java.util.stream.Stream;

  26. import org.hipparchus.exception.LocalizedCoreFormats;
  27. import org.hipparchus.util.FastMath;
  28. import org.orekit.errors.OrekitIllegalArgumentException;
  29. import org.orekit.errors.OrekitIllegalStateException;
  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.     /** Generator to use for yet non-cached data. */
  52.     private final TimeStampedGenerator<T> generator;

  53.     /** Number of entries in a neighbors array. */
  54.     private final int neighborsSize;

  55.     /** Independent time slots cached. */
  56.     private final List<Slot> slots;

  57.     /** Number of calls to the getNeighbors method. */
  58.     private final AtomicInteger getNeighborsCalls;

  59.     /** Number of calls to the generate method. */
  60.     private final AtomicInteger generateCalls;

  61.     /** Number of evictions. */
  62.     private final AtomicInteger evictions;

  63.     /** Global lock. */
  64.     private final ReadWriteLock lock;

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

  77.         // safety check
  78.         if (maxSlots < 1) {
  79.             throw new OrekitIllegalArgumentException(LocalizedCoreFormats.NUMBER_TOO_SMALL, maxSlots, 1);
  80.         }
  81.         if (neighborsSize < 2) {
  82.             throw new OrekitIllegalArgumentException(OrekitMessages.NOT_ENOUGH_CACHED_NEIGHBORS,
  83.                                                      neighborsSize, 2);
  84.         }

  85.         this.reference         = new AtomicReference<AbsoluteDate>();
  86.         this.maxSlots          = maxSlots;
  87.         this.maxSpan           = maxSpan;
  88.         this.newSlotQuantumGap = FastMath.round(newSlotInterval / QUANTUM_STEP);
  89.         this.generator         = generator;
  90.         this.neighborsSize     = neighborsSize;
  91.         this.slots             = new ArrayList<Slot>(maxSlots);
  92.         this.getNeighborsCalls = new AtomicInteger(0);
  93.         this.generateCalls     = new AtomicInteger(0);
  94.         this.evictions         = new AtomicInteger(0);
  95.         this.lock              = new ReentrantReadWriteLock();

  96.     }

  97.     /** Get the generator.
  98.      * @return generator
  99.      */
  100.     public TimeStampedGenerator<T> getGenerator() {
  101.         return generator;
  102.     }

  103.     /** Get the maximum number of independent cached time slots.
  104.      * @return maximum number of independent cached time slots
  105.      */
  106.     public int getMaxSlots() {
  107.         return maxSlots;
  108.     }

  109.     /** Get the maximum duration span in seconds of one slot.
  110.      * @return maximum duration span in seconds of one slot
  111.      */
  112.     public double getMaxSpan() {
  113.         return maxSpan;
  114.     }

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

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

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

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

  162.     /** Get the number of slots in use.
  163.      * @return number of slots in use
  164.      */
  165.     public int getSlots() {

  166.         lock.readLock().lock();
  167.         try {
  168.             return slots.size();
  169.         } finally {
  170.             lock.readLock().unlock();
  171.         }

  172.     }

  173.     /** Get the total number of entries cached.
  174.      * @return total number of entries cached
  175.      */
  176.     public int getEntries() {

  177.         lock.readLock().lock();
  178.         try {
  179.             int entries = 0;
  180.             for (final Slot slot : slots) {
  181.                 entries += slot.getEntries();
  182.             }
  183.             return entries;
  184.         } finally {
  185.             lock.readLock().unlock();
  186.         }

  187.     }

  188.     /** Get the earliest cached entry.
  189.      * @return earliest cached entry
  190.      * @exception IllegalStateException if the cache has no slots at all
  191.      * @see #getSlots()
  192.      */
  193.     public T getEarliest() throws IllegalStateException {

  194.         lock.readLock().lock();
  195.         try {
  196.             if (slots.isEmpty()) {
  197.                 throw new OrekitIllegalStateException(OrekitMessages.NO_CACHED_ENTRIES);
  198.             }
  199.             return slots.get(0).getEarliest();
  200.         } finally {
  201.             lock.readLock().unlock();
  202.         }

  203.     }

  204.     /** Get the latest cached entry.
  205.      * @return latest cached entry
  206.      * @exception IllegalStateException if the cache has no slots at all
  207.      * @see #getSlots()
  208.      */
  209.     public T getLatest() throws IllegalStateException {

  210.         lock.readLock().lock();
  211.         try {
  212.             if (slots.isEmpty()) {
  213.                 throw new OrekitIllegalStateException(OrekitMessages.NO_CACHED_ENTRIES);
  214.             }
  215.             return slots.get(slots.size() - 1).getLatest();
  216.         } finally {
  217.             lock.readLock().unlock();
  218.         }

  219.     }

  220.     /** Get the fixed size of the arrays to be returned by {@link #getNeighbors(AbsoluteDate)}.
  221.      * @return size of the array
  222.      */
  223.     public int getNeighborsSize() {
  224.         return neighborsSize;
  225.     }

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

  246.         lock.readLock().lock();
  247.         try {
  248.             getNeighborsCalls.incrementAndGet();
  249.             final long dateQuantum = quantum(central);
  250.             return selectSlot(central, dateQuantum).getNeighbors(central, dateQuantum);
  251.         } finally {
  252.             lock.readLock().unlock();
  253.         }

  254.     }

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

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

  278.         Slot selected = null;

  279.         int index = slots.isEmpty() ? 0 : slotIndex(dateQuantum);
  280.         if (slots.isEmpty() ||
  281.             slots.get(index).getEarliestQuantum() > dateQuantum + newSlotQuantumGap ||
  282.             slots.get(index).getLatestQuantum()   < dateQuantum - newSlotQuantumGap) {
  283.             // no existing slot is suitable

  284.             // upgrade the read lock to a write lock so we can change the list of available slots
  285.             lock.readLock().unlock();
  286.             lock.writeLock().lock();

  287.             try {
  288.                 // check slots again as another thread may have changed
  289.                 // the list while we were waiting for the write lock
  290.                 index = slots.isEmpty() ? 0 : slotIndex(dateQuantum);
  291.                 if (slots.isEmpty() ||
  292.                     slots.get(index).getEarliestQuantum() > dateQuantum + newSlotQuantumGap ||
  293.                     slots.get(index).getLatestQuantum()   < dateQuantum - newSlotQuantumGap) {

  294.                     // we really need to create a new slot in the current thread
  295.                     // (no other threads have created it while we were waiting for the lock)
  296.                     if ((!slots.isEmpty()) &&
  297.                         slots.get(index).getLatestQuantum() < dateQuantum - newSlotQuantumGap) {
  298.                         ++index;
  299.                     }

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

  302.                         // select the oldest accessed slot for eviction
  303.                         int evict = 0;
  304.                         for (int i = 0; i < slots.size(); ++i) {
  305.                             if (slots.get(i).getLastAccess() < slots.get(evict).getLastAccess()) {
  306.                                 evict = i;
  307.                             }
  308.                         }

  309.                         // evict the selected slot
  310.                         evictions.incrementAndGet();
  311.                         slots.remove(evict);

  312.                         if (evict < index) {
  313.                             // adjust index of created slot as it was shifted by the eviction
  314.                             index--;
  315.                         }
  316.                     }

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

  318.                 }

  319.             } finally {
  320.                 // downgrade back to a read lock
  321.                 lock.readLock().lock();
  322.                 lock.writeLock().unlock();
  323.             }
  324.         }

  325.         selected = slots.get(index);


  326.         return selected;

  327.     }

  328.     /** Get the index of the slot in which a date could be cached.
  329.      * <p>
  330.      * We own a global read lock while calling this method.
  331.      * </p>
  332.      * @param dateQuantum quantum of the date to search for
  333.      * @return the slot in which the date could be cached
  334.      */
  335.     private int slotIndex(final long dateQuantum) {

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

  352.         return iInf;

  353.     }

  354.     /** Time slot. */
  355.     private final class Slot {

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

  358.         /** Earliest quantum. */
  359.         private AtomicLong earliestQuantum;

  360.         /** Latest quantum. */
  361.         private AtomicLong latestQuantum;

  362.         /** Index from a previous recent call. */
  363.         private AtomicInteger guessedIndex;

  364.         /** Last access time. */
  365.         private AtomicLong lastAccess;

  366.         /** Simple constructor.
  367.          * @param date central date for initial entries to insert in the slot
  368.          * @exception TimeStampedCacheException if entries are not chronologically
  369.          * sorted or if new data cannot be generated
  370.          */
  371.         Slot(final AbsoluteDate date) throws TimeStampedCacheException {

  372.             // allocate cache
  373.             this.cache = new ArrayList<Entry>();

  374.             // set up first entries
  375.             AbsoluteDate generationDate = date;

  376.             generateCalls.incrementAndGet();
  377.             for (final T entry : generateAndCheck(null, generationDate)) {
  378.                 cache.add(new Entry(entry, quantum(entry.getDate())));
  379.             }
  380.             earliestQuantum = new AtomicLong(cache.get(0).getQuantum());
  381.             latestQuantum   = new AtomicLong(cache.get(cache.size() - 1).getQuantum());

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

  384.                 final AbsoluteDate entry0 = cache.get(0).getData().getDate();
  385.                 final AbsoluteDate entryN = cache.get(cache.size() - 1).getData().getDate();
  386.                 generateCalls.incrementAndGet();

  387.                 final AbsoluteDate existingDate;
  388.                 if (entryN.getDate().durationFrom(date) <= date.durationFrom(entry0.getDate())) {
  389.                     // generate additional point at the end of the slot
  390.                     existingDate = entryN;
  391.                     generationDate = entryN.getDate().shiftedBy(getMeanStep() * (neighborsSize - cache.size()));
  392.                     appendAtEnd(generateAndCheck(existingDate, generationDate));
  393.                 } else {
  394.                     // generate additional point at the start of the slot
  395.                     existingDate = entry0;
  396.                     generationDate = entry0.getDate().shiftedBy(-getMeanStep() * (neighborsSize - cache.size()));
  397.                     insertAtStart(generateAndCheck(existingDate, generationDate));
  398.                 }

  399.             }

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

  402.         }

  403.         /** Get the earliest entry contained in the slot.
  404.          * @return earliest entry contained in the slot
  405.          */
  406.         public T getEarliest() {
  407.             return cache.get(0).getData();
  408.         }

  409.         /** Get the quantum of the earliest date contained in the slot.
  410.          * @return quantum of the earliest date contained in the slot
  411.          */
  412.         public long getEarliestQuantum() {
  413.             return earliestQuantum.get();
  414.         }

  415.         /** Get the latest entry contained in the slot.
  416.          * @return latest entry contained in the slot
  417.          */
  418.         public T getLatest() {
  419.             return cache.get(cache.size() - 1).getData();
  420.         }

  421.         /** Get the quantum of the latest date contained in the slot.
  422.          * @return quantum of the latest date contained in the slot
  423.          */
  424.         public long getLatestQuantum() {
  425.             return latestQuantum.get();
  426.         }

  427.         /** Get the number of entries contained din the slot.
  428.          * @return number of entries contained din the slot
  429.          */
  430.         public int getEntries() {
  431.             return cache.size();
  432.         }

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

  446.         /** Get last access time of slot.
  447.          * @return last known access time
  448.          */
  449.         public long getLastAccess() {
  450.             return lastAccess.get();
  451.         }

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

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

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

  477.                 // upgrade the read lock to a write lock so we can change the list of available slots
  478.                 lock.readLock().unlock();
  479.                 lock.writeLock().lock();

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

  488.                             // estimate which data we need to be generated
  489.                             final double step = getMeanStep();
  490.                             final AbsoluteDate existingDate;
  491.                             final AbsoluteDate generationDate;
  492.                             final boolean simplyRebalance;
  493.                             if (firstNeighbor < 0) {
  494.                                 existingDate    = cache.get(0).getData().getDate();
  495.                                 generationDate  = existingDate.getDate().shiftedBy(step * firstNeighbor);
  496.                                 simplyRebalance = existingDate.getDate().compareTo(central) <= 0;
  497.                             } else {
  498.                                 existingDate    = cache.get(cache.size() - 1).getData().getDate();
  499.                                 generationDate  = existingDate.getDate().shiftedBy(step * (firstNeighbor + neighborsSize - cache.size()));
  500.                                 simplyRebalance = existingDate.getDate().compareTo(central) >= 0;
  501.                             }
  502.                             generateCalls.incrementAndGet();

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

  520.                         } else {
  521.                             loop = false;
  522.                         }
  523.                     }
  524.                 } finally {
  525.                     // downgrade back to a read lock
  526.                     lock.readLock().lock();
  527.                     lock.writeLock().unlock();
  528.                 }

  529.             }

  530.             if (firstNeighbor + neighborsSize > cache.size()) {
  531.                 // we end up with a non-balanced neighborhood,
  532.                 // adjust the start point to fit within the cache
  533.                 firstNeighbor = cache.size() - neighborsSize;
  534.             }
  535.             if (firstNeighbor < 0) {
  536.                 firstNeighbor = 0;
  537.             }
  538.             final Stream.Builder<T> builder = Stream.builder();
  539.             for (int i = 0; i < neighborsSize; ++i) {
  540.                 builder.accept(cache.get(firstNeighbor + i).getData());
  541.             }

  542.             return builder.build();

  543.         }

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

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

  576.             // quick guesses have failed, we need to perform a full blown search
  577.             if (dateQuantum < getEarliestQuantum()) {
  578.                 // date if before the first entry
  579.                 return -1;
  580.             } else if (dateQuantum > getLatestQuantum()) {
  581.                 // date is after the last entry
  582.                 return cache.size();
  583.             } else {

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

  603.                 guessedIndex.set(iInf);
  604.                 return iInf;

  605.             }

  606.         }

  607.         /** Insert data at slot start.
  608.          * @param data data to insert
  609.          * @exception TimeStampedCacheException if new data cannot be generated
  610.          */
  611.         private void insertAtStart(final List<T> data) throws TimeStampedCacheException {

  612.             // insert data at start
  613.             boolean inserted = false;
  614.             final long q0 = earliestQuantum.get();
  615.             for (int i = 0; i < data.size(); ++i) {
  616.                 final long quantum = quantum(data.get(i).getDate());
  617.                 if (quantum < q0) {
  618.                     cache.add(i, new Entry(data.get(i), quantum));
  619.                     inserted = true;
  620.                 } else {
  621.                     break;
  622.                 }
  623.             }

  624.             if (!inserted) {
  625.                 throw new TimeStampedCacheException(OrekitMessages.UNABLE_TO_GENERATE_NEW_DATA_BEFORE,
  626.                                                               cache.get(0).getData().getDate());
  627.             }

  628.             // evict excess data at end
  629.             final AbsoluteDate t0 = cache.get(0).getData().getDate();
  630.             while (cache.size() > neighborsSize &&
  631.                    cache.get(cache.size() - 1).getData().getDate().durationFrom(t0) > maxSpan) {
  632.                 cache.remove(cache.size() - 1);
  633.             }

  634.             // update boundaries
  635.             earliestQuantum.set(cache.get(0).getQuantum());
  636.             latestQuantum.set(cache.get(cache.size() - 1).getQuantum());

  637.         }

  638.         /** Append data at slot end.
  639.          * @param data data to append
  640.          * @exception TimeStampedCacheException if new data cannot be generated
  641.          */
  642.         private void appendAtEnd(final List<T> data) throws TimeStampedCacheException {

  643.             // append data at end
  644.             boolean appended = false;
  645.             final long qn = latestQuantum.get();
  646.             final int  n  = cache.size();
  647.             for (int i = data.size() - 1; i >= 0; --i) {
  648.                 final long quantum = quantum(data.get(i).getDate());
  649.                 if (quantum > qn) {
  650.                     cache.add(n, new Entry(data.get(i), quantum));
  651.                     appended = true;
  652.                 } else {
  653.                     break;
  654.                 }
  655.             }

  656.             if (!appended) {
  657.                 throw new TimeStampedCacheException(OrekitMessages.UNABLE_TO_GENERATE_NEW_DATA_AFTER,
  658.                                                     cache.get(cache.size() - 1).getData().getDate());
  659.             }

  660.             // evict excess data at start
  661.             final AbsoluteDate tn = cache.get(cache.size() - 1).getData().getDate();
  662.             while (cache.size() > neighborsSize &&
  663.                    tn.durationFrom(cache.get(0).getData().getDate()) > maxSpan) {
  664.                 cache.remove(0);
  665.             }

  666.             // update boundaries
  667.             earliestQuantum.set(cache.get(0).getQuantum());
  668.             latestQuantum.set(cache.get(cache.size() - 1).getQuantum());

  669.         }

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

  693.         /** Container for entries. */
  694.         private class Entry {

  695.             /** Entry data. */
  696.             private final T data;

  697.             /** Global quantum of the entry. */
  698.             private final long quantum;

  699.             /** Simple constructor.
  700.              * @param data entry data
  701.              * @param quantum entry quantum
  702.              */
  703.             Entry(final T data, final long quantum) {
  704.                 this.quantum = quantum;
  705.                 this.data  = data;
  706.             }

  707.             /** Get the quantum.
  708.              * @return quantum
  709.              */
  710.             public long getQuantum() {
  711.                 return quantum;
  712.             }

  713.             /** Get the data.
  714.              * @return data
  715.              */
  716.             public T getData() {
  717.                 return data;
  718.             }

  719.         }
  720.     }

  721. }