aboutsummaryrefslogtreecommitdiff
path: root/guava-tests/test/com/google/common/cache/LocalCacheMapComputeTest.java
blob: 61f5fed2d1eba71fada147bae4ebfd94608faadd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
/*
 * Copyright (C) 2017 The Guava Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.common.cache;

import static com.google.common.truth.Truth.assertThat;

import com.google.common.util.concurrent.UncheckedExecutionException;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.IntConsumer;
import java.util.stream.IntStream;
import junit.framework.TestCase;

/** Test Java8 map.compute in concurrent cache context. */
public class LocalCacheMapComputeTest extends TestCase {
  final int count = 10000;
  final String delimiter = "-";
  final String key = "key";
  Cache<String, String> cache;

  // helper
  private static void doParallelCacheOp(int count, IntConsumer consumer) {
    IntStream.range(0, count).parallel().forEach(consumer);
  }

  @Override
  public void setUp() throws Exception {
    super.setUp();
    this.cache =
        CacheBuilder.newBuilder()
            .expireAfterAccess(500000, TimeUnit.MILLISECONDS)
            .maximumSize(count)
            .build();
  }

  public void testComputeIfAbsent() {
    // simultaneous insertion for same key, expect 1 winner
    doParallelCacheOp(
        count,
        n -> {
          cache.asMap().computeIfAbsent(key, k -> "value" + n);
        });
    assertEquals(1, cache.size());
  }

  public void testComputeIfAbsentEviction() {
    // b/80241237

    Cache<String, String> c = CacheBuilder.newBuilder().maximumSize(1).build();

    assertThat(c.asMap().computeIfAbsent("hash-1", k -> "")).isEqualTo("");
    assertThat(c.asMap().computeIfAbsent("hash-1", k -> "")).isEqualTo("");
    assertThat(c.asMap().computeIfAbsent("hash-1", k -> "")).isEqualTo("");
    assertThat(c.size()).isEqualTo(1);
    assertThat(c.asMap().computeIfAbsent("hash-2", k -> "")).isEqualTo("");
  }

  public void testComputeEviction() {
    // b/80241237

    Cache<String, String> c = CacheBuilder.newBuilder().maximumSize(1).build();

    assertThat(c.asMap().compute("hash-1", (k, v) -> "a")).isEqualTo("a");
    assertThat(c.asMap().compute("hash-1", (k, v) -> "b")).isEqualTo("b");
    assertThat(c.asMap().compute("hash-1", (k, v) -> "c")).isEqualTo("c");
    assertThat(c.size()).isEqualTo(1);
    assertThat(c.asMap().computeIfAbsent("hash-2", k -> "")).isEqualTo("");
  }

  public void testComputeIfPresent() {
    cache.put(key, "1");
    // simultaneous update for same key, expect count successful updates
    doParallelCacheOp(
        count,
        n -> {
          cache.asMap().computeIfPresent(key, (k, v) -> v + delimiter + n);
        });
    assertEquals(1, cache.size());
    assertThat(cache.getIfPresent(key).split(delimiter)).hasLength(count + 1);
  }

  public void testComputeIfPresentRemove() {
    List<RemovalNotification<Integer, Integer>> notifications = new ArrayList<>();
    Cache<Integer, Integer> cache =
        CacheBuilder.newBuilder()
            .removalListener(
                new RemovalListener<Integer, Integer>() {
                  @Override
                  public void onRemoval(RemovalNotification<Integer, Integer> notification) {
                    notifications.add(notification);
                  }
                })
            .build();
    cache.put(1, 2);

    // explicitly remove the existing value
    cache.asMap().computeIfPresent(1, (key, value) -> null);
    assertThat(notifications).hasSize(1);
    CacheTesting.checkEmpty(cache);

    // ensure no zombie entry remains
    cache.asMap().computeIfPresent(1, (key, value) -> null);
    assertThat(notifications).hasSize(1);
    CacheTesting.checkEmpty(cache);
  }

  public void testUpdates() {
    cache.put(key, "1");
    // simultaneous update for same key, some null, some non-null
    doParallelCacheOp(
        count,
        n -> {
          cache.asMap().compute(key, (k, v) -> n % 2 == 0 ? v + delimiter + n : null);
        });
    assertTrue(1 >= cache.size());
  }

  public void testCompute() {
    cache.put(key, "1");
    // simultaneous deletion
    doParallelCacheOp(
        count,
        n -> {
          cache.asMap().compute(key, (k, v) -> null);
        });
    assertEquals(0, cache.size());
  }

  public void testComputeWithLoad() {
    Queue<RemovalNotification<String, String>> notifications = new ConcurrentLinkedQueue<>();
    cache =
        CacheBuilder.newBuilder()
            .removalListener(
                new RemovalListener<String, String>() {
                  @Override
                  public void onRemoval(RemovalNotification<String, String> notification) {
                    notifications.add(notification);
                  }
                })
            .expireAfterAccess(500000, TimeUnit.MILLISECONDS)
            .maximumSize(count)
            .build();

    cache.put(key, "1");
    // simultaneous load and deletion
    doParallelCacheOp(
        count,
        n -> {
          try {
            String unused = cache.get(key, () -> key);
            cache.asMap().compute(key, (k, v) -> null);
          } catch (ExecutionException e) {
            throw new UncheckedExecutionException(e);
          }
        });

    CacheTesting.checkEmpty(cache);
    for (RemovalNotification<String, String> entry : notifications) {
      assertThat(entry.getKey()).isNotNull();
      assertThat(entry.getValue()).isNotNull();
    }
  }

  public void testComputeExceptionally() {
    try {
      doParallelCacheOp(
          count,
          n -> {
            cache
                .asMap()
                .compute(
                    key,
                    (k, v) -> {
                      throw new RuntimeException();
                    });
          });
      fail("Should not get here");
    } catch (RuntimeException ex) {
    }
  }
}