View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.commons.jcs3.jcache.extras.loader;
20  
21  import org.apache.commons.jcs3.jcache.extras.InternalCacheRule;
22  import org.junit.Rule;
23  import org.junit.Test;
24  
25  import javax.cache.Cache;
26  import javax.cache.configuration.Configuration;
27  import javax.cache.configuration.MutableConfiguration;
28  import javax.cache.integration.CacheLoaderException;
29  import java.util.HashSet;
30  import java.util.concurrent.atomic.AtomicInteger;
31  
32  import static java.util.Arrays.asList;
33  import static org.junit.Assert.assertEquals;
34  import static org.junit.Assert.assertFalse;
35  
36  public class CacheLoaderAdapterTest
37  {
38      @Rule
39      public final InternalCacheRule rule = new InternalCacheRule(this);
40  
41      private final AtomicInteger count = new AtomicInteger(0);
42      private final Configuration<?, ?> config = new MutableConfiguration<String, String>().setStoreByValue(false).setReadThrough(true).setCacheLoaderFactory(new CacheLoaderAdapter<String, String>()
43      {
44          @Override
45          public String load(final String key) throws CacheLoaderException
46          {
47              count.incrementAndGet();
48              return key;
49          }
50      });
51      private Cache<String, String> cache;
52  
53      @Test
54      public void checkLoadAll()
55      {
56          assertFalse(cache.iterator().hasNext());
57          assertEquals("foo", cache.get("foo"));
58  
59          count.decrementAndGet();
60          cache.loadAll(new HashSet<>(asList("a", "b")), true, null);
61          int retries = 100;
62          while (retries-- > 0 && count.get() != 2)
63          {
64              try
65              {
66                  Thread.sleep(20);
67              }
68              catch (final InterruptedException e)
69              {
70                  Thread.interrupted();
71              }
72          }
73          assertEquals(2, count.get());
74          assertEquals("a", cache.get("a"));
75          assertEquals("b", cache.get("b"));
76          assertEquals(2, count.get());
77      }
78  }