View Javadoc

1   package com.atlassian.vcache;
2   
3   import java.time.Duration;
4   import java.util.Optional;
5   import javax.annotation.Nonnull;
6   
7   import com.atlassian.annotations.PublicApi;
8   
9   /**
10   * Builder for creating {@link JvmCacheSettings} instances.
11   *
12   * @since 1.0
13   */
14  @PublicApi
15  public class JvmCacheSettingsBuilder
16  {
17      private Optional<Integer> maxEntries = Optional.empty();
18      private Optional<Duration> defaultTtl = Optional.empty();
19  
20      /**
21       * Creates an instance with no settings initialised.
22       */
23      public JvmCacheSettingsBuilder()
24      {
25      }
26  
27      /**
28       * Constructs an instance initialised with the supplied settings.
29       * @param settings the settings to configure the instance with.
30       */
31      public JvmCacheSettingsBuilder(JvmCacheSettings settings)
32      {
33          this.maxEntries = settings.getMaxEntries();
34          this.defaultTtl = settings.getDefaultTtl();
35      }
36  
37      /**
38       * Returns a new {@link JvmCacheSettings} instance configured using the supplied settings.
39       * @return a new {@link JvmCacheSettings} instance configured using the supplied settings.
40       */
41      @Nonnull
42      public JvmCacheSettings build()
43      {
44          return new JvmCacheSettings(maxEntries, defaultTtl);
45      }
46  
47      /**
48       * Specifies the maximum number of entries to be held in the cache. Must not be a negative number.
49       * When <tt>0</tt> is specified, the entries will be evicted immediately after being loaded into the cache.
50       *
51       * @param max the number of entries to be held in the cache
52       * @return the builder
53       * @throws IllegalArgumentException thrown if <tt>max</tt> is negative
54       */
55      @Nonnull
56      public JvmCacheSettingsBuilder maxEntries(int max)
57      {
58          if (max < 0)
59          {
60              throw new IllegalArgumentException("maxEntries must not be negative, passed: " + max);
61          }
62  
63          maxEntries = Optional.of(max);
64          return this;
65      }
66  
67      /**
68       * Specifies the default time-to-live for entries to be held in the cache. Must be a positive number.
69       *
70       * @param ttl the default time-to-live for entries to be held in the cache
71       * @return the builder
72       * @throws IllegalArgumentException thrown if <tt>ttl</tt> is not positive
73       */
74      @Nonnull
75      public JvmCacheSettingsBuilder defaultTtl(Duration ttl)
76      {
77          if (ttl.getNano() <= 0)
78          {
79              throw new IllegalArgumentException("ttl must be greater than zero, passed: " + ttl);
80          }
81  
82          defaultTtl = Optional.of(ttl);
83          return this;
84      }
85  }