SynchronizedCache.java

  1. /*
  2.  *    Copyright 2009-2024 the original author or authors.
  3.  *
  4.  *    Licensed under the Apache License, Version 2.0 (the "License");
  5.  *    you may not use this file except in compliance with the License.
  6.  *    You may obtain a copy of the License at
  7.  *
  8.  *       https://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  *    Unless required by applicable law or agreed to in writing, software
  11.  *    distributed under the License is distributed on an "AS IS" BASIS,
  12.  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  *    See the License for the specific language governing permissions and
  14.  *    limitations under the License.
  15.  */
  16. package org.apache.ibatis.cache.decorators;

  17. import java.util.concurrent.locks.ReentrantLock;

  18. import org.apache.ibatis.cache.Cache;

  19. /**
  20.  * @author Clinton Begin
  21.  */
  22. public class SynchronizedCache implements Cache {

  23.   private final ReentrantLock lock = new ReentrantLock();
  24.   private final Cache delegate;

  25.   public SynchronizedCache(Cache delegate) {
  26.     this.delegate = delegate;
  27.   }

  28.   @Override
  29.   public String getId() {
  30.     return delegate.getId();
  31.   }

  32.   @Override
  33.   public int getSize() {
  34.     lock.lock();
  35.     try {
  36.       return delegate.getSize();
  37.     } finally {
  38.       lock.unlock();
  39.     }
  40.   }

  41.   @Override
  42.   public void putObject(Object key, Object object) {
  43.     lock.lock();
  44.     try {
  45.       delegate.putObject(key, object);
  46.     } finally {
  47.       lock.unlock();
  48.     }
  49.   }

  50.   @Override
  51.   public Object getObject(Object key) {
  52.     lock.lock();
  53.     try {
  54.       return delegate.getObject(key);
  55.     } finally {
  56.       lock.unlock();
  57.     }
  58.   }

  59.   @Override
  60.   public Object removeObject(Object key) {
  61.     lock.lock();
  62.     try {
  63.       return delegate.removeObject(key);
  64.     } finally {
  65.       lock.unlock();
  66.     }
  67.   }

  68.   @Override
  69.   public void clear() {
  70.     lock.lock();
  71.     try {
  72.       delegate.clear();
  73.     } finally {
  74.       lock.unlock();
  75.     }
  76.   }

  77.   @Override
  78.   public int hashCode() {
  79.     return delegate.hashCode();
  80.   }

  81.   @Override
  82.   public boolean equals(Object obj) {
  83.     return delegate.equals(obj);
  84.   }

  85. }