Ripristinati lock e unlock

This commit is contained in:
2025-04-24 11:02:53 +02:00
parent 794612fc16
commit 4e97fa1d56
5 changed files with 173 additions and 161 deletions

View File

@@ -12,7 +12,7 @@ import java.util.concurrent.locks.ReentrantLock;
@Service @Service
public class EmsDBConst { public class EmsDBConst {
// private final ReentrantLock datiAziendaLock = new ReentrantLock(); private final ReentrantLock datiAziendaLock = new ReentrantLock();
private HashMap<String, Const> datiAziendaBindingTable = new HashMap<String, Const>() {{ private HashMap<String, Const> datiAziendaBindingTable = new HashMap<String, Const>() {{
}}; }};
@@ -28,24 +28,24 @@ public class EmsDBConst {
public Const getConsts(String dbName) { public Const getConsts(String dbName) {
String aziendaUp = dbName.toUpperCase(); String aziendaUp = dbName.toUpperCase();
// datiAziendaLock.lock(); datiAziendaLock.lock();
try {
if (!datiAziendaBindingTable.containsKey(aziendaUp)) { if (!datiAziendaBindingTable.containsKey(aziendaUp)) {
datiAziendaBindingTable.put(aziendaUp, new Const()); datiAziendaBindingTable.put(aziendaUp, new Const());
} }
final Const aConst = datiAziendaBindingTable.get(aziendaUp); return datiAziendaBindingTable.get(aziendaUp);
// datiAziendaLock.unlock(); } finally {
datiAziendaLock.unlock();
return aConst; }
} }
public void destroyAll() { public void destroyAll() {
// datiAziendaLock.lock(); datiAziendaLock.lock();
datiAziendaBindingTable = new HashMap<>(); datiAziendaBindingTable = new HashMap<>();
// datiAziendaLock.unlock(); datiAziendaLock.unlock();
} }
public static class Const { public static class Const {
private String applicationDbName; private String applicationDbName;

View File

@@ -19,6 +19,7 @@ import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Service @Service
@@ -32,7 +33,7 @@ public class UnitaTerritorialiService {
// Data di ultima modifica // Data di ultima modifica
private Instant lastModifiedSource = Instant.MIN; private Instant lastModifiedSource = Instant.MIN;
// Locker per la sincronizzazione // Locker per la sincronizzazione
// private final ReentrantLock updateLocker = new ReentrantLock(); private final ReentrantLock updateLocker = new ReentrantLock();
// Dati transcodificati // Dati transcodificati
private List<IstatComuneDataRow> dataSource = new ArrayList<>(); private List<IstatComuneDataRow> dataSource = new ArrayList<>();
private List<Regione> regioni = new ArrayList<>(); private List<Regione> regioni = new ArrayList<>();
@@ -77,13 +78,13 @@ public class UnitaTerritorialiService {
return; return;
} }
// updateLocker.lock(); updateLocker.lock();
try (InputStream streamIstat = connectionIstat.getInputStream()) { try (InputStream streamIstat = connectionIstat.getInputStream()) {
if (updateServiceData(streamIstat)) { if (updateServiceData(streamIstat)) {
lastModifiedSource = Instant.now(); // Recupera la data di modifica dal server lastModifiedSource = Instant.now(); // Recupera la data di modifica dal server
} }
} finally { } finally {
// updateLocker.unlock(); updateLocker.unlock();
} }
} }

View File

@@ -15,6 +15,7 @@ import java.sql.SQLException;
import java.util.*; import java.util.*;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
@Component @Component
public class BasicConnectionPool { public class BasicConnectionPool {
@@ -29,21 +30,21 @@ public class BasicConnectionPool {
private final ConcurrentHashMap<String, AtomicInteger> extraConnectionCounters = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, AtomicInteger> extraConnectionCounters = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Set<String>> activeConnectionNames = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, Set<String>> activeConnectionNames = new ConcurrentHashMap<>();
// private final ReentrantLock poolLock = new ReentrantLock(); private final ReentrantLock poolLock = new ReentrantLock();
public void init() throws Exception { public void init() throws Exception {
// poolLock.lock(); poolLock.lock();
try { try {
closeAllConnections(); closeAllConnections();
int poolSize = calculatePoolSize(); int poolSize = calculatePoolSize();
initializeConnections(poolSize); initializeConnections(poolSize);
} finally { } finally {
// poolLock.unlock(); poolLock.unlock();
} }
} }
private void closeAllConnections() { private void closeAllConnections() {
// poolLock.lock(); poolLock.lock();
try { try {
// Chiude tutte le connessioni esistenti // Chiude tutte le connessioni esistenti
connectionPool.values().forEach(connections -> connectionPool.values().forEach(connections ->
@@ -57,7 +58,7 @@ public class BasicConnectionPool {
extraConnectionCounters.clear(); extraConnectionCounters.clear();
activeConnectionNames.clear(); activeConnectionNames.clear();
} finally { } finally {
// poolLock.unlock(); poolLock.unlock();
} }
} }
@@ -127,21 +128,16 @@ public class BasicConnectionPool {
return null; return null;
} }
// poolLock.lock(); poolLock.lock();
try { try {
if (!connectionPool.containsKey(dbName)|| connectionPool.get(dbName).isEmpty()) { if (!connectionPool.containsKey(dbName) || connectionPool.get(dbName).isEmpty()) {
return createExtraConnection(profileName); return createExtraConnection(profileName);
} }
List<DataSource> pool = connectionPool.get(dbName); List<DataSource> pool = connectionPool.get(dbName);
List<DataSource> used = usedConnections.get(dbName); List<DataSource> used = usedConnections.get(dbName);
DataSource ds; DataSource ds = pool.remove(0);
try {
ds = pool.remove(0);
} catch (IndexOutOfBoundsException ex) {
return createExtraConnection(profileName);
}
if (ds.isClosed()) { if (ds.isClosed()) {
String oldName = ds.getApplicationName(); String oldName = ds.getApplicationName();
@@ -157,7 +153,7 @@ public class BasicConnectionPool {
logger.trace("Assigned connection: {} for database: {}", ds.getApplicationName(), dbName); logger.trace("Assigned connection: {} for database: {}", ds.getApplicationName(), dbName);
return ds; return ds;
} finally { } finally {
// poolLock.unlock(); poolLock.unlock();
} }
} }
@@ -167,7 +163,7 @@ public class BasicConnectionPool {
return false; return false;
} }
// poolLock.lock(); poolLock.lock();
try { try {
String currentCatalog = ds.getConnection().getCatalog(); String currentCatalog = ds.getConnection().getCatalog();
AvailableConnectionsModel model = findConnectionModel(profileName); AvailableConnectionsModel model = findConnectionModel(profileName);
@@ -183,13 +179,13 @@ public class BasicConnectionPool {
return handleConnectionRelease(ds); return handleConnectionRelease(ds);
} finally { } finally {
// poolLock.unlock(); poolLock.unlock();
} }
} }
private DataSource createExtraConnection(String profileName) throws Exception { private DataSource createExtraConnection(String profileName) throws Exception {
String dbName = settingsModel.getDbNameFromProfileDb(profileName); String dbName = settingsModel.getDbNameFromProfileDb(profileName);
// poolLock.lock(); poolLock.lock();
try { try {
// Calcola il numero totale di connessioni esistenti // Calcola il numero totale di connessioni esistenti
int baseCount = connectionPool.get(dbName).size() + usedConnections.get(dbName).size(); int baseCount = connectionPool.get(dbName).size() + usedConnections.get(dbName).size();
@@ -201,7 +197,6 @@ public class BasicConnectionPool {
// Verifica se la connessione esiste già // Verifica se la connessione esiste già
if (activeConnectionNames.get(dbName).contains(connectionName)) { if (activeConnectionNames.get(dbName).contains(connectionName)) {
logger.warn("Extra connection name collision detected: {}", connectionName); logger.warn("Extra connection name collision detected: {}", connectionName);
// extraConnectionCounters.get(dbName).decrementAndGet();
return createExtraConnection(profileName); // Riprova con un nuovo nome return createExtraConnection(profileName); // Riprova con un nuovo nome
} }
@@ -212,7 +207,7 @@ public class BasicConnectionPool {
logger.trace("Created extra connection: {} for database: {}", connectionName, dbName); logger.trace("Created extra connection: {} for database: {}", connectionName, dbName);
return ds; return ds;
} finally { } finally {
// poolLock.unlock(); poolLock.unlock();
} }
} }

View File

@@ -23,6 +23,7 @@ import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Service @Service
@@ -35,7 +36,7 @@ public class MultiDBTransactionManager implements AutoCloseable {
private List<AdvancedDataSource> dbDatasources = new ArrayList<>(); private List<AdvancedDataSource> dbDatasources = new ArrayList<>();
private DataSource dataSource; private DataSource dataSource;
// private final ReentrantLock datasourcesLock = new ReentrantLock(); private final ReentrantLock datasourcesLock = new ReentrantLock();
@Autowired @Autowired
private BasicConnectionPool connectionPool; private BasicConnectionPool connectionPool;
@@ -89,7 +90,6 @@ public class MultiDBTransactionManager implements AutoCloseable {
this.setPrimaryDs(profileDb); this.setPrimaryDs(profileDb);
} catch (Exception ex) { } catch (Exception ex) {
logger.error("Errore durante la connessione al DB.", ex); logger.error("Errore durante la connessione al DB.", ex);
// throw ex;
} }
} }
@@ -135,7 +135,8 @@ public class MultiDBTransactionManager implements AutoCloseable {
} }
} }
// datasourcesLock.lock(); datasourcesLock.lock();
try {
dbDatasources.add(new AdvancedDataSource(profileName, dataSource, isDistributore, isInternalDb)); dbDatasources.add(new AdvancedDataSource(profileName, dataSource, isDistributore, isInternalDb));
if (isDistributore) { if (isDistributore) {
@@ -147,8 +148,9 @@ public class MultiDBTransactionManager implements AutoCloseable {
}) })
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
} finally {
// datasourcesLock.unlock(); datasourcesLock.unlock();
}
} }
} }
@@ -243,7 +245,8 @@ public class MultiDBTransactionManager implements AutoCloseable {
} }
public void closeAll() throws Exception { public void closeAll() throws Exception {
// datasourcesLock.lock(); datasourcesLock.lock();
try {
if (dbDatasources != null && !dbDatasources.isEmpty()) { if (dbDatasources != null && !dbDatasources.isEmpty()) {
for (AdvancedDataSource advancedDataSource : dbDatasources) { for (AdvancedDataSource advancedDataSource : dbDatasources) {
@@ -262,15 +265,16 @@ public class MultiDBTransactionManager implements AutoCloseable {
logger.error("UnexpectedConnectionSwitchException: " + advancedDataSource.getProfileName(), e); logger.error("UnexpectedConnectionSwitchException: " + advancedDataSource.getProfileName(), e);
} }
if(dbPrimary != null && advancedDataSource.getDataSource() == dbPrimary.getDataSource()) if (dbPrimary != null && advancedDataSource.getDataSource() == dbPrimary.getDataSource())
dbPrimary = null; dbPrimary = null;
} }
dbDatasources.clear(); dbDatasources.clear();
} }
} finally {
// datasourcesLock.unlock(); datasourcesLock.unlock();
}
} }

View File

@@ -38,13 +38,13 @@ public class UserCacheService {
private final HashMap<String, List<UserDTO>> cachedUsers = new HashMap<>(); private final HashMap<String, List<UserDTO>> cachedUsers = new HashMap<>();
//private final ReentrantLock cacheLock = new ReentrantLock(); private final ReentrantLock cacheLock = new ReentrantLock();
boolean canStart = false; boolean canStart = false;
@PostContextConstruct(priority = 10) @PostContextConstruct(priority = 10)
private void init() { private void init() {
if(UtilityDebug.isDebugExecution()) internalCacheUpdate(true); if (UtilityDebug.isDebugExecution()) internalCacheUpdate(true);
canStart = !UtilityDebug.isDebugExecution(); canStart = !UtilityDebug.isDebugExecution();
} }
@@ -54,7 +54,7 @@ public class UserCacheService {
} }
private void internalCacheUpdate(boolean forceStart) { private void internalCacheUpdate(boolean forceStart) {
if(!forceStart && !canStart) return; if (!forceStart && !canStart) return;
List<AvailableConnectionsModel> availableConnectionsModels = List<AvailableConnectionsModel> availableConnectionsModels =
settingsModel.getAvailableConnectionsWithoutDuplicatedProfiles(true); settingsModel.getAvailableConnectionsWithoutDuplicatedProfiles(true);
@@ -103,7 +103,8 @@ public class UserCacheService {
} }
public @Nullable UserDTO retrieveUser(String dbName, String md5User) { public @Nullable UserDTO retrieveUser(String dbName, String md5User) {
//cacheLock.lock(); cacheLock.lock();
try {
List<UserDTO> users = cachedUsers.getOrDefault(dbName, null); List<UserDTO> users = cachedUsers.getOrDefault(dbName, null);
if (users == null || users.isEmpty()) if (users == null || users.isEmpty())
@@ -119,12 +120,15 @@ public class UserCacheService {
}) })
.findFirst(); .findFirst();
//cacheLock.unlock();
return foundUser.orElse(null); return foundUser.orElse(null);
} finally {
cacheLock.unlock();
}
} }
public @Nullable UserDTO retrieveUser(String dbName, String username, String password, IntegryApplicationEnum application) { public @Nullable UserDTO retrieveUser(String dbName, String username, String password, IntegryApplicationEnum application) {
//cacheLock.lock(); cacheLock.lock();
try {
List<UserDTO> users = cachedUsers.getOrDefault(dbName, null); List<UserDTO> users = cachedUsers.getOrDefault(dbName, null);
if (users == null || users.isEmpty()) if (users == null || users.isEmpty())
@@ -145,14 +149,17 @@ public class UserCacheService {
(application == IntegryApplicationEnum.GESTIONALE_BASE && x.isInternal()))) (application == IntegryApplicationEnum.GESTIONALE_BASE && x.isInternal())))
.findFirst(); .findFirst();
//cacheLock.unlock();
return foundUser.orElse(null); return foundUser.orElse(null);
} finally {
cacheLock.unlock();
}
} }
public @Nullable UserDTO retrieveUserData(String profileDb, String username, IntegryApplicationEnum application) { public @Nullable UserDTO retrieveUserData(String profileDb, String username, IntegryApplicationEnum application) {
cacheLock.lock();
try {
String dbName = settingsModel.getDbNameFromProfileDb(profileDb); String dbName = settingsModel.getDbNameFromProfileDb(profileDb);
//cacheLock.lock();
List<UserDTO> users = cachedUsers.getOrDefault(dbName, null); List<UserDTO> users = cachedUsers.getOrDefault(dbName, null);
if (users == null || users.isEmpty()) if (users == null || users.isEmpty())
@@ -166,14 +173,17 @@ public class UserCacheService {
(application == IntegryApplicationEnum.WMS && x.isWeb()) || (application == IntegryApplicationEnum.WMS && x.isWeb()) ||
(application == IntegryApplicationEnum.GESTIONALE_BASE && x.isInternal()))) (application == IntegryApplicationEnum.GESTIONALE_BASE && x.isInternal())))
.findFirst(); .findFirst();
//cacheLock.unlock();
return foundUser.orElse(null); return foundUser.orElse(null);
} finally {
cacheLock.unlock();
}
} }
public void discoverAllUsers(MultiDBTransactionManager multiDBTransactionManager) throws Exception { public void discoverAllUsers(MultiDBTransactionManager multiDBTransactionManager) throws Exception {
//cacheLock.lock(); cacheLock.lock();
try {
List<Callable<Void>> calls = new ArrayList<>(); List<Callable<Void>> calls = new ArrayList<>();
for (final AdvancedDataSource advancedDataSource : multiDBTransactionManager.getActiveConnections()) { for (final AdvancedDataSource advancedDataSource : multiDBTransactionManager.getActiveConnections()) {
@@ -217,13 +227,15 @@ public class UserCacheService {
} }
taskExecutorService.executeTasks(calls); taskExecutorService.executeTasks(calls);
//cacheLock.unlock(); } finally {
cacheLock.unlock();
}
} }
public void invalidateCache() { public void invalidateCache() {
//cacheLock.lock(); cacheLock.lock();
this.cachedUsers.clear(); this.cachedUsers.clear();
//cacheLock.unlock(); cacheLock.unlock();
this.internalCacheUpdate(); this.internalCacheUpdate();
} }