Refactor synchronized to ReentrantLock (#2081)

This commit is contained in:
Rob Bygrave authored and GitHub committed 2020-10-16 00:20:42 +13:00
1 parent 0faa6a8efd
commit 14181932ec
30 files changed
+368 -185

No files matched your search

+12 -13
View File
@@ -8,6 +8,7 @@ import org.slf4j.LoggerFactory;
import javax.persistence.PersistenceException;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
/**
* Holds Database instances.
@@ -22,17 +23,11 @@ final class DbContext {
private static final DbContext INSTANCE = new DbContext();
/**
* Cache for fast concurrent read access.
*/
private final ConcurrentHashMap<String, Database> concMap = new ConcurrentHashMap<>();
/**
* Cache for synchronized read, creation and put. Protected by the monitor object.
*/
private final HashMap<String, Database> syncMap = new HashMap<>();
private final Object monitor = new Object();
private final ReentrantLock lock = new ReentrantLock(false);
/**
* The 'default' Database.
@@ -91,27 +86,28 @@ final class DbContext {
if (name == null || name.isEmpty()) {
return defaultDatabase;
}
// non-synchronized read
Database server = concMap.get(name);
if (server != null) {
return server;
}
// synchronized read, create and put
return getWithCreate(name);
}
/**
* Synchronized read, create and put of Databases.
* Read, create and put of Databases.
*/
private Database getWithCreate(String name) {
synchronized (monitor) {
lock.lock();
try {
Database server = syncMap.get(name);
if (server == null) {
// register when creating server this way
server = EbeanServerFactory.create(name);
server = DatabaseFactory.create(name);
register(server, false);
}
return server;
} finally {
lock.unlock();
}
}
@@ -123,12 +119,15 @@ final class DbContext {
}
private void registerWithName(String name, Database server, boolean isDefault) {
synchronized (monitor) {
lock.lock();
try {
concMap.put(name, server);
syncMap.put(name, server);
if (isDefault) {
defaultDatabase = server;
}
} finally {
lock.unlock();
}
}
@@ -39,28 +39,28 @@ public class EbeanServerFactory {
* Call this prior to creating any EbeanServer instances or alternatively set the
* ContainerConfig on the ServerConfig when creating the first EbeanServer instance.
*/
public static synchronized void initialiseContainer(ContainerConfig containerConfig) {
public static void initialiseContainer(ContainerConfig containerConfig) {
DatabaseFactory.initialiseContainer(containerConfig);
}
/**
* Create using ebean.properties to configure the database.
*/
public static synchronized EbeanServer create(String name) {
public static EbeanServer create(String name) {
return (EbeanServer)DatabaseFactory.create(name);
}
/**
* Create using the ServerConfig object to configure the database.
*/
public static synchronized EbeanServer create(ServerConfig config) {
public static EbeanServer create(ServerConfig config) {
return (EbeanServer)DatabaseFactory.create(config);
}
/**
* Create using the ServerConfig additionally specifying a classLoader to use as the context class loader.
*/
public static synchronized EbeanServer createWithContextClassLoader(ServerConfig config, ClassLoader classLoader) {
public static EbeanServer createWithContextClassLoader(ServerConfig config, ClassLoader classLoader) {
return (EbeanServer)DatabaseFactory.createWithContextClassLoader(config, classLoader);
}
@@ -70,7 +70,7 @@ public class EbeanServerFactory {
* This is typically invoked via JVM shutdown hook and not explicitly called.
* </p>
*/
public static synchronized void shutdown() {
public static void shutdown() {
DatabaseFactory.shutdown();
}
@@ -1,5 +1,7 @@
package io.ebean.bean;
import java.util.concurrent.locks.Lock;
/**
* Loads a entity bean.
* <p>
@@ -18,4 +20,9 @@ public interface BeanLoader {
*/
void loadBean(EntityBeanIntercept ebi);
/**
* Obtain a lock on the loader.
*/
Lock lock();
}
@@ -14,6 +14,8 @@ import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* This is the object added to every entity bean using byte code enhancement.
@@ -30,6 +32,8 @@ public final class EntityBeanIntercept implements Serializable {
private static final int STATE_REFERENCE = 1;
private static final int STATE_LOADED = 2;
private transient final ReentrantLock lock = new ReentrantLock(false);
private transient NodeUsageCollector nodeUsageCollector;
private transient PersistenceContext persistenceContext;
@@ -803,7 +807,8 @@ public final class EntityBeanIntercept implements Serializable {
* Load the bean when it is a reference.
*/
protected void loadBean(int loadProperty) {
synchronized (this) {
lock.lock();
try {
if (beanLoader == null) {
final Database database = DB.byName(ebeanServerName);
if (database == null) {
@@ -811,14 +816,19 @@ public final class EntityBeanIntercept implements Serializable {
}
// For stand alone reference bean or after deserialisation lazy load
// using the ebeanServer. Synchronise only on the bean.
loadBeanInternal(loadProperty, database.getPluginApi());
loadBeanInternal(loadProperty, database.getPluginApi().beanLoader());
return;
}
} finally {
lock.unlock();
}
synchronized (beanLoader) {
final Lock lock = beanLoader.lock();
try {
// Lazy loading using LoadBeanContext which supports batch loading
// Synchronise on the beanLoader (a 'node' of the LoadBeanContext 'tree')
loadBeanInternal(loadProperty, beanLoader);
} finally {
lock.unlock();
}
}
@@ -2,11 +2,16 @@ package io.ebean.bean;
import io.ebean.Database;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* BeanLoader used when single beans are loaded (which is usually not ideal / N+1).
*/
public abstract class SingleBeanLoader implements BeanLoader {
private final ReentrantLock lock = new ReentrantLock(false);
protected final Database database;
SingleBeanLoader(Database database) {
@@ -18,6 +23,12 @@ public abstract class SingleBeanLoader implements BeanLoader {
return database.getName();
}
@Override
public Lock lock() {
lock.lock();
return lock;
}
/**
* Single bean lazy loaded when bean from L2 cache.
*/
@@ -45,4 +56,18 @@ public abstract class SingleBeanLoader implements BeanLoader {
database.getPluginApi().loadBeanRef(ebi);
}
}
/**
* Single bean lazy loaded when a reference bean.
*/
public static class Dflt extends SingleBeanLoader {
public Dflt(Database database) {
super(database);
}
@Override
public void loadBean(EntityBeanIntercept ebi) {
database.getPluginApi().loadBean(ebi);
}
}
}
@@ -7,6 +7,7 @@ import io.ebean.bean.BeanCollectionLoader;
import io.ebean.bean.EntityBean;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;
/**
* Base class for List Set and Map implementations of BeanCollection.
@@ -15,6 +16,8 @@ abstract class AbstractBeanCollection<E> implements BeanCollection<E> {
private static final long serialVersionUID = 3365725236140187588L;
protected final ReentrantLock lock = new ReentrantLock(false);
protected boolean readOnly;
protected boolean disableLazyLoad;
@@ -115,7 +115,8 @@ public final class BeanList<E> extends AbstractBeanCollection<E> implements List
}
private void initClear() {
synchronized (this) {
lock.lock();
try {
if (list == null) {
if (!disableLazyLoad && modifyListening) {
lazyLoadCollection(true);
@@ -123,11 +124,14 @@ public final class BeanList<E> extends AbstractBeanCollection<E> implements List
list = new ArrayList<>();
}
}
} finally {
lock.unlock();
}
}
private void init() {
synchronized (this) {
lock.lock();
try {
if (list == null) {
if (disableLazyLoad) {
list = new ArrayList<>();
@@ -135,6 +139,8 @@ public final class BeanList<E> extends AbstractBeanCollection<E> implements List
lazyLoadCollection(false);
}
}
} finally {
lock.unlock();
}
}
@@ -121,7 +121,8 @@ public final class BeanMap<K, E> extends AbstractBeanCollection<E> implements Ma
}
private void initClear() {
synchronized (this) {
lock.lock();
try {
if (map == null) {
if (!disableLazyLoad && modifyListening) {
lazyLoadCollection(true);
@@ -129,11 +130,14 @@ public final class BeanMap<K, E> extends AbstractBeanCollection<E> implements Ma
map = new LinkedHashMap<>();
}
}
} finally {
lock.unlock();
}
}
private void init() {
synchronized (this) {
lock.lock();
try {
if (map == null) {
if (disableLazyLoad) {
map = new LinkedHashMap<>();
@@ -141,6 +145,8 @@ public final class BeanMap<K, E> extends AbstractBeanCollection<E> implements Ma
lazyLoadCollection(false);
}
}
} finally {
lock.unlock();
}
}
@@ -114,7 +114,8 @@ public final class BeanSet<E> extends AbstractBeanCollection<E> implements Set<E
}
private void initClear() {
synchronized (this) {
lock.lock();
try {
if (set == null) {
if (!disableLazyLoad && modifyListening) {
lazyLoadCollection(true);
@@ -122,11 +123,14 @@ public final class BeanSet<E> extends AbstractBeanCollection<E> implements Set<E
set = new LinkedHashSet<>();
}
}
} finally {
lock.unlock();
}
}
private void init() {
synchronized (this) {
lock.lock();
try {
if (set == null) {
if (disableLazyLoad) {
set = new LinkedHashSet<>();
@@ -134,6 +138,8 @@ public final class BeanSet<E> extends AbstractBeanCollection<E> implements Set<E
lazyLoadCollection(true);
}
}
} finally {
lock.unlock();
}
}
@@ -6,25 +6,27 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
/**
* List that copies itself on first write access. Needed to keep memory footprint low and the ability
* to modify lists from cache.
*
*
* @author Roland Praml, FOCONIS AG
*/
public final class CopyOnFirstWriteList<E> extends AbstractList<E> implements List<E>, Serializable {
private static final long serialVersionUID = 1L;
private final ReentrantLock lock = new ReentrantLock(false);
/**
* The underlying List implementation.
*/
private List<E> list;
public CopyOnFirstWriteList(List<E> list) {
super();
this.list = list;
@@ -166,14 +168,17 @@ public final class CopyOnFirstWriteList<E> extends AbstractList<E> implements Li
public int lastIndexOf(Object o) {
return list.lastIndexOf(o);
}
private void checkCopyOnWrite() {
if (!copied) {
synchronized (this) {
lock.lock();
try {
if (!copied) {
list = new ArrayList<>(list);
copied = true;
}
} finally {
lock.unlock();
}
}
}
@@ -16,6 +16,7 @@ import java.util.Collections;
import java.util.List;
import java.util.NavigableSet;
import java.util.TreeSet;
import java.util.concurrent.locks.ReentrantLock;
/**
* Database sequence based IdGenerator.
@@ -24,15 +25,9 @@ public abstract class SequenceIdGenerator implements PlatformIdGenerator {
protected static final Logger logger = LoggerFactory.getLogger("io.ebean.SEQ");
/**
* Used to synchronise the idList access.
*/
protected final Object monitor = new Object();
private final ReentrantLock lock = new ReentrantLock(false);
/**
* Used to synchronise background loading (loadBatchInBackground).
*/
protected final Object backgroundLoadMonitor = new Object();
private final ReentrantLock loadLock = new ReentrantLock(false);
/**
* The actual sequence name.
@@ -97,7 +92,8 @@ public abstract class SequenceIdGenerator implements PlatformIdGenerator {
*/
@Override
public Object nextId(Transaction t) {
synchronized (monitor) {
lock.lock();
try {
int size = idList.size();
if (size > 0) {
maybeLoadMoreInBackground(size);
@@ -105,6 +101,8 @@ public abstract class SequenceIdGenerator implements PlatformIdGenerator {
loadMore(allocationSize);
}
return idList.pollFirst();
} finally {
lock.unlock();
}
}
@@ -118,8 +116,11 @@ public abstract class SequenceIdGenerator implements PlatformIdGenerator {
private void loadMore(int requestSize) {
List<Long> newIds = getMoreIds(requestSize);
synchronized (monitor) {
lock.lock();
try {
idList.addAll(newIds);
} finally {
lock.unlock();
}
}
@@ -127,23 +128,26 @@ public abstract class SequenceIdGenerator implements PlatformIdGenerator {
* Load another batch of Id's using a background thread.
*/
protected void loadInBackground(final int requestSize) {
// single threaded processing...
synchronized (backgroundLoadMonitor) {
loadLock.lock();
try {
if (currentlyBackgroundLoading) {
// skip as already background loading
logger.debug("... skip background sequence load (another load in progress)");
return;
}
currentlyBackgroundLoading = true;
backgroundExecutor.execute(() -> {
loadMore(requestSize);
synchronized (backgroundLoadMonitor) {
loadLock.lock();
try {
currentlyBackgroundLoading = false;
} finally {
loadLock.unlock();
}
});
} finally {
loadLock.lock();
}
}
@@ -11,6 +11,7 @@ import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
/**
* Manages the shutdown of the JVM Runtime.
@@ -22,6 +23,8 @@ public final class ShutdownManager {
private static final Logger logger = LoggerFactory.getLogger(ShutdownManager.class);
private static final ReentrantLock lock = new ReentrantLock(false);
private static final List<Database> databases = new ArrayList<>();
private static final ShutdownHook shutdownHook = new ShutdownHook();
@@ -56,9 +59,11 @@ public final class ShutdownManager {
* Return true if the system is in the process of stopping.
*/
public static boolean isStopping() {
//noinspection SynchronizationOnStaticField
synchronized (databases) {
lock.lock();
try {
return stopping;
} finally {
lock.unlock();
}
}
@@ -74,15 +79,15 @@ public final class ShutdownManager {
* </p>
*/
public static void deregisterShutdownHook() {
//noinspection SynchronizationOnStaticField
synchronized (databases) {
try {
Runtime.getRuntime().removeShutdownHook(shutdownHook);
} catch (IllegalStateException ex) {
if (!ex.getMessage().equals("Shutdown in progress")) {
throw ex;
}
lock.lock();
try {
Runtime.getRuntime().removeShutdownHook(shutdownHook);
} catch (IllegalStateException ex) {
if (!ex.getMessage().equals("Shutdown in progress")) {
throw ex;
}
} finally {
lock.unlock();
}
}
@@ -90,18 +95,18 @@ public final class ShutdownManager {
* Register the shutdown hook with the Runtime.
*/
protected static void registerShutdownHook() {
//noinspection SynchronizationOnStaticField
synchronized (databases) {
try {
String value = System.getProperty("ebean.registerShutdownHook");
if (value == null || !value.trim().equalsIgnoreCase("false")) {
Runtime.getRuntime().addShutdownHook(shutdownHook);
}
} catch (IllegalStateException ex) {
if (!ex.getMessage().equals("Shutdown in progress")) {
throw ex;
}
lock.lock();
try {
String value = System.getProperty("ebean.registerShutdownHook");
if (value == null || !value.trim().equalsIgnoreCase("false")) {
Runtime.getRuntime().addShutdownHook(shutdownHook);
}
} catch (IllegalStateException ex) {
if (!ex.getMessage().equals("Shutdown in progress")) {
throw ex;
}
} finally {
lock.unlock();
}
}
@@ -112,8 +117,8 @@ public final class ShutdownManager {
* </p>
*/
public static void shutdown() {
//noinspection SynchronizationOnStaticField
synchronized (databases) {
lock.lock();
try {
if (stopping) {
// Already run shutdown...
return;
@@ -157,6 +162,8 @@ public final class ShutdownManager {
if ("true".equalsIgnoreCase(System.getProperty("ebean.datasource.deregisterAllDrivers", "false"))) {
deregisterAllJdbcDrivers();
}
} finally {
lock.unlock();
}
}
@@ -178,9 +185,11 @@ public final class ShutdownManager {
* Register an ebeanServer to be shutdown when the JVM is shutdown.
*/
public static void registerDatabase(Database server) {
//noinspection SynchronizationOnStaticField
synchronized (databases) {
lock.lock();
try {
databases.add(server);
} finally {
lock.unlock();
}
}
@@ -191,9 +200,11 @@ public final class ShutdownManager {
* </p>
*/
public static void unregisterDatabase(Database server) {
//noinspection SynchronizationOnStaticField
synchronized (databases) {
lock.lock();
try {
databases.remove(server);
} finally {
lock.unlock();
}
}
@@ -12,7 +12,7 @@ import java.util.List;
/**
* Extensions to Database API made available to plugins.
*/
public interface SpiServer extends EbeanServer, BeanLoader {
public interface SpiServer extends EbeanServer {
/**
* Return the DatabaseConfig.
@@ -54,6 +54,11 @@ public interface SpiServer extends EbeanServer, BeanLoader {
*/
DataSource getReadOnlyDataSource();
/**
* Return a BeanLoader.
*/
BeanLoader beanLoader();
/**
* Invoke lazy loading on this single bean (reference bean).
*/