001// -------------------------------------------------------------------------------- 002// Copyright 2002-2024 Echo Three, LLC 003// 004// Licensed under the Apache License, Version 2.0 (the "License"); 005// you may not use this file except in compliance with the License. 006// You may obtain a copy of the License at 007// 008// http://www.apache.org/licenses/LICENSE-2.0 009// 010// Unless required by applicable law or agreed to in writing, software 011// distributed under the License is distributed on an "AS IS" BASIS, 012// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013// See the License for the specific language governing permissions and 014// limitations under the License. 015// -------------------------------------------------------------------------------- 016 017package com.echothree.util.server.persistence; 018 019import org.apache.commons.logging.Log; 020import org.apache.commons.logging.LogFactory; 021 022public class ThreadCaches { 023 024 private static Log log = LogFactory.getLog(ThreadCaches.class); 025 private static final ThreadLocal<Caches> cacheses = new ThreadLocal<>(); 026 027 private ThreadCaches() {} 028 029 public static Caches currentCaches() { 030 Caches caches = cacheses.get(); 031 032 if(caches == null) { 033 caches = CachesFactory.getInstance().getCaches(); 034 cacheses.set(caches); 035 036 if(PersistenceDebugFlags.LogThreads) { 037 log.info("Created Caches for Thread " + Thread.currentThread().getName()); 038 } 039 } 040 041 return caches; 042 } 043 044 static class PreservedCaches { 045 private Caches caches; 046 047 private PreservedCaches(Caches caches) { 048 this.caches = caches; 049 } 050 } 051 052 // Utilize via ThreadUtils 053 static ThreadCaches.PreservedCaches preserve() { 054 Caches caches = cacheses.get(); 055 056 if(caches != null) { 057 cacheses.remove(); 058 059 if(PersistenceDebugFlags.LogThreads) { 060 log.info("Preserved Caches for Thread " + Thread.currentThread().getName()); 061 } 062 } 063 064 return new ThreadCaches.PreservedCaches(caches); 065 } 066 067 // Utilize via ThreadUtils 068 static void restore(ThreadCaches.PreservedCaches preservedCaches) { 069 var caches = preservedCaches.caches; 070 071 if(caches != null) { 072 cacheses.set(caches); 073 074 if(PersistenceDebugFlags.LogThreads) { 075 log.info("Restored Caches for Thread " + Thread.currentThread().getName()); 076 } 077 } 078 } 079 080 // Utilize via ThreadUtils 081 public static void close() { 082 Caches caches = cacheses.get(); 083 084 if(caches != null) { 085 caches.close(); 086 cacheses.remove(); 087 088 if(PersistenceDebugFlags.LogThreads) { 089 log.info("Closed Caches for Thread " + Thread.currentThread().getName()); 090 } 091 } 092 } 093 094}