Skip to content

Commit

Permalink
synchronized to lock (#820)
Browse files Browse the repository at this point in the history
use Lock instead of synchronized keyword
  • Loading branch information
zt9788 authored Oct 1, 2023
1 parent f8c11c5 commit 0b88e1a
Show file tree
Hide file tree
Showing 10 changed files with 155 additions and 30 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,27 @@
import org.w3c.dom.Element;

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

/**
* @author <a href="mailto:areyouok@gmail.com">huangli</a>
*/
public class CacheAnnotationParser implements BeanDefinitionParser {

private final ReentrantLock reentrantLock = new ReentrantLock();

@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
doParse(element, parserContext);
reentrantLock.lock();
try {
doParse(element, parserContext);
}finally {
reentrantLock.unlock();
}
return null;
}

private synchronized void doParse(Element element, ParserContext parserContext) {
private void doParse(Element element, ParserContext parserContext) {
String[] basePackages = StringUtils.tokenizeToStringArray(element.getAttribute("base-package"), ",; \t\n");
AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(parserContext, element);
if (!parserContext.getRegistry().containsBeanDefinition(CacheAdvisor.CACHE_ADVISOR_BEAN_NAME)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

/**
* Created on 2016/12/9.
Expand All @@ -38,6 +39,7 @@ public class CreateCacheAnnotationBeanPostProcessor extends AutowiredAnnotationB
private ConfigurableListableBeanFactory beanFactory;

private final Map<String, InjectionMetadata> injectionMetadataCache = new ConcurrentHashMap<String, InjectionMetadata>();
private final ReentrantLock reentrantLock = new ReentrantLock();

@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
Expand Down Expand Up @@ -77,7 +79,8 @@ private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz
// Quick check on the concurrent map first, with minimal locking.
InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
synchronized (this.injectionMetadataCache) {
reentrantLock.lock();
try{
metadata = this.injectionMetadataCache.get(cacheKey);
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
if (metadata != null) {
Expand All @@ -91,6 +94,8 @@ private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz
"] for autowiring metadata: could not find class that it depends on", err);
}
}
}finally {
reentrantLock.unlock();
}
}
return metadata;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Function;

Expand All @@ -36,13 +37,17 @@ public abstract class AbstractCache<K, V> implements Cache<K, V> {
private volatile ConcurrentHashMap<Object, LoaderLock> loaderMap;

protected volatile boolean closed;
private static final ReentrantLock reentrantLock = new ReentrantLock();

ConcurrentHashMap<Object, LoaderLock> initOrGetLoaderMap() {
if (loaderMap == null) {
synchronized (this) {
reentrantLock.lock();
try {
if (loaderMap == null) {
loaderMap = new ConcurrentHashMap<>();
}
}finally {
reentrantLock.unlock();
}
}
return loaderMap;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,14 @@
*/
package com.alicp.jetcache.embedded;

import com.alicp.jetcache.AbstractCache;
import com.alicp.jetcache.CacheConfig;
import com.alicp.jetcache.CacheGetResult;
import com.alicp.jetcache.CacheResult;
import com.alicp.jetcache.CacheResultCode;
import com.alicp.jetcache.CacheValueHolder;
import com.alicp.jetcache.MultiGetResult;
import com.alicp.jetcache.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;
import java.util.stream.Collectors;

Expand All @@ -28,6 +23,8 @@ public abstract class AbstractEmbeddedCache<K, V> extends AbstractCache<K, V> {

protected abstract InnerMap createAreaCache();

private final ReentrantLock lock = new ReentrantLock();

public AbstractEmbeddedCache(EmbeddedCacheConfig<K, V> config) {
this.config = config;
innerMap = createAreaCache();
Expand Down Expand Up @@ -61,7 +58,8 @@ protected CacheGetResult<V> parseHolderResult(CacheValueHolder<V> holder) {
} else if (now >= holder.getExpireTime()) {
return CacheGetResult.EXPIRED_WITHOUT_MSG;
} else {
synchronized (holder) {
lock.lock();
try{
long accessTime = holder.getAccessTime();
if (config.isExpireAfterAccess()) {
long expireAfterAccess = config.getExpireAfterAccessInMillis();
Expand All @@ -70,6 +68,8 @@ protected CacheGetResult<V> parseHolderResult(CacheValueHolder<V> holder) {
}
}
holder.setAccessTime(now);
}finally {
lock.unlock();
}

return new CacheGetResult(CacheResultCode.SUCCESS, null, holder);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import java.util.LinkedList;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
* Created on 2017/2/28.
Expand All @@ -16,20 +17,25 @@
class Cleaner {

static LinkedList<WeakReference<LinkedHashMapCache>> linkedHashMapCaches = new LinkedList<>();
private static final ReentrantLock reentrantLock = new ReentrantLock();

static {
ScheduledExecutorService executorService = JetCacheExecutor.defaultExecutor();
executorService.scheduleWithFixedDelay(() -> run(), 60, 60, TimeUnit.SECONDS);
}

static void add(LinkedHashMapCache cache) {
synchronized (linkedHashMapCaches) {
reentrantLock.lock();
try{
linkedHashMapCaches.add(new WeakReference<>(cache));
}finally {
reentrantLock.unlock();
}
}

static void run() {
synchronized (linkedHashMapCaches) {
reentrantLock.lock();
try{
Iterator<WeakReference<LinkedHashMapCache>> it = linkedHashMapCaches.iterator();
while (it.hasNext()) {
WeakReference<LinkedHashMapCache> ref = it.next();
Expand All @@ -40,6 +46,8 @@ static void run() {
c.cleanExpiredEntry();
}
}
}finally {
reentrantLock.unlock();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
* @author <a href="mailto:areyouok@gmail.com">huangli</a>
Expand All @@ -28,7 +30,7 @@ protected void addToCleaner() {

@Override
protected InnerMap createAreaCache() {
return new LRUMap(config.getLimit(), this);
return new LRUMap(config.getLimit());
}

@Override
Expand All @@ -46,12 +48,13 @@ public void cleanExpiredEntry() {
final class LRUMap extends LinkedHashMap implements InnerMap {

private final int max;
private Object lock;
// private final Object lockObj;
private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

public LRUMap(int max, Object lock) {
public LRUMap(int max) {
super((int) (max * 1.4f), 0.75f, true);
this.max = max;
this.lock = lock;
// this.lockObj = lockObj;
}

@Override
Expand All @@ -60,7 +63,9 @@ protected boolean removeEldestEntry(Map.Entry eldest) {
}

void cleanExpiredEntry() {
synchronized (lock) {
Lock lock = readWriteLock.writeLock();
lock.lock();
try{
for (Iterator it = entrySet().iterator(); it.hasNext();) {
Map.Entry en = (Map.Entry) it.next();
Object value = en.getValue();
Expand All @@ -78,74 +83,104 @@ void cleanExpiredEntry() {
}
}
}
}finally {
lock.unlock();
}
}

@Override
public Object getValue(Object key) {
synchronized (lock) {
Lock lock = readWriteLock.readLock();
lock.lock();
try{
return get(key);
}finally {
lock.unlock();
}
}

@Override
public Map getAllValues(Collection keys) {
Lock lock = readWriteLock.readLock();
lock.lock();
Map values = new HashMap();
synchronized (lock) {
try{
for (Object key : keys) {
Object v = get(key);
if (v != null) {
values.put(key, v);
}
}
}finally {
lock.unlock();
}
return values;
}

@Override
public void putValue(Object key, Object value) {
synchronized (lock) {
Lock lock = readWriteLock.writeLock();
lock.lock();
try{
put(key, value);
}finally {
lock.unlock();
}
}

@Override
public void putAllValues(Map map) {
synchronized (lock) {
Lock lock = readWriteLock.writeLock();
lock.lock();
try{
Set<Map.Entry> set = map.entrySet();
for (Map.Entry en : set) {
put(en.getKey(), en.getValue());
}
}finally {
lock.unlock();
}
}

@Override
public boolean removeValue(Object key) {
synchronized (lock) {
Lock lock = readWriteLock.writeLock();
lock.lock();
try{
return remove(key) != null;
}finally {
lock.unlock();
}
}

@Override
public void removeAllValues(Collection keys) {
synchronized (lock) {
Lock lock = readWriteLock.writeLock();
lock.lock();
try{
for (Object k : keys) {
remove(k);
}
}finally {
lock.unlock();
}
}

@Override
@SuppressWarnings("unchecked")
public boolean putIfAbsentValue(Object key, Object value) {
synchronized (lock) {
Lock lock = readWriteLock.writeLock();
lock.lock();
try{
CacheValueHolder h = (CacheValueHolder) get(key);
if (h == null || parseHolderResult(h).getResultCode() == CacheResultCode.EXPIRED) {
put(key, value);
return true;
} else {
return false;
}
}finally {
lock.unlock();
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.alicp.jetcache.anno.SerialPolicy;

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

/**
* @author <a href="mailto:areyouok@gmail.com">huangli</a>
Expand All @@ -14,6 +15,7 @@ public class DecoderMap {

private final ConcurrentHashMap<Integer, AbstractValueDecoder> decoderMap = new ConcurrentHashMap<>();
private volatile boolean inited = false;
private final ReentrantLock reentrantLock = new ReentrantLock();

private static final DecoderMap instance = new DecoderMap();

Expand Down Expand Up @@ -42,7 +44,8 @@ public void initDefaultDecoder() {
if (inited) {
return;
}
synchronized (this) {
reentrantLock.lock();
try {
if (inited) {
return;
}
Expand All @@ -51,6 +54,8 @@ public void initDefaultDecoder() {
register(SerialPolicy.IDENTITY_NUMBER_KRYO5, Kryo5ValueDecoder.INSTANCE);
// register(SerialPolicy.IDENTITY_NUMBER_FASTJSON2, Fastjson2ValueDecoder.INSTANCE);
inited = true;
}finally {
reentrantLock.unlock();
}
}

Expand Down
Loading

0 comments on commit 0b88e1a

Please sign in to comment.