GenericTimeStampedCache.java

  1. /* Copyright 2002-2016 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.OrekitIllegalArgumentException;
  30. import org.orekit.errors.OrekitIllegalStateException;
  31. import org.orekit.errors.OrekitMessages;
  32. import org.orekit.errors.TimeStampedCacheException;
  33. import org.orekit.time.AbsoluteDate;
  34. import org.orekit.time.TimeStamped;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  102.     }

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

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

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

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

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

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

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

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

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

  178.     }

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

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

  193.     }

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

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

  209.     }

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

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

  225.     }

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

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

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

  261.     }

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

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

  285.         Slot selected = null;

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

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

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

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

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

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

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

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

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

  325.                 }

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

  332.         selected = slots.get(index);


  333.         return selected;

  334.     }

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

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

  359.         return iInf;

  360.     }

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

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

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

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

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

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

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

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

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

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

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

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

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

  406.             }

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

  409.         }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  536.             }

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

  550.             return array;

  551.         }

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

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

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

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

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

  613.             }

  614.         }

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

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

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

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

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

  645.         }

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

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

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

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

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

  677.         }

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

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

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

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

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

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

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

  727.         }
  728.     }

  729. }