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