Java geek
Related reading:
Java Concurrent programming (1) Knowledge map Java concurrent programming (2) Atomic Java concurrent programming (3) Visibility Java concurrent programming (4) Sequential Java concurrent programming (5) Introduction to Creating threads Java concurrent programming (6) Synchronized usage Java Concurrency programming Introduction (7) Easy to understand wait and Notify and use scenarios Java concurrency programming Introduction (8) Thread lifecycle Java concurrency programming Introduction (9) Deadlock and deadlock bit Java concurrency programming Introduction (10) lock optimization Introduction to Concurrent Programming in Java (11) Flow limiting scenarios and Spring Flow Limiting Schemes Introduction to Concurrent programming in Java (12) Producer and Consumer Patterns – Code Templates Introduction to Concurrent programming in Java (14) CountDownLatch application Scenarios Introduction to Concurrent Programming (CyclicBarrier) Introduction to Concurrent programming (CyclicBarrier) Introduction to Concurrent programming in Java (CyclicBarrier) Introduction to Concurrent programming in Java (CyclicBarrier) Introduction to Concurrent programming in Java (CyclicBarrier) Introduction to Concurrent programming in Java (CyclicBarrier) Introduction to Concurrent programming in Java (CyclicBarrier) Introduction to Concurrent programming in Java (CyclicBarrier) Introduction to Concurrent programming in Java (CyclicBarrier) Introduction to Concurrent programming in Java (CyclicBarrier Java Concurrent programming Introduction (19) Asynchronous task scheduling tool CompleteFeature Java concurrent programming Introduction (20) Common locking scenarios and locking tools
Read/write lock
When it comes to read/write locks, we can think of lock separation, which is one of the lock optimization methods. The realization effect is read/write mutually exclusive, read/write mutually exclusive, write mutually exclusive.
The read/write lock itself is relatively simple. Here is an example to look at the use of the read/write lock.
2.CacheManager is a cache management class. Cache-related operations are centrally managed through CacheManager.
3.CacheKey is a constant-defining class that defines the key for each cache, such as the id type CacheKey, the industry CacheKey, etc., accessed by a defined constant key when accessing a specified cache.
B, Show me code
I, the Cache. Java
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/ * * *@ClassName Cache
* @DescriptionCaching abstract classes *@AuthorSonorous leaf *@Date 2019/10/6 10:59
* @Version1.0 * * * / javashizhan.com
public abstract class Cache<K.V> {
final Map<K, V> m = new HashMap<K,V>();
final ReadWriteLock rwl = new ReentrantReadWriteLock();
final Lock r = rwl.readLock();
final Lock w = rwl.writeLock();
public V get(K key) {
r.lock();
try {
return m.get(key);
} finally{ r.unlock(); }}public V put(K key, V value) {
w.lock();
try {
return m.put(key, value);
} finally{ w.unlock(); }}public V remove(K key) {
w.lock();
try {
return m.remove(key);
} finally{ w.unlock(); }}/** * template method, call the subclass implementation of init method */
void _init(a) {
w.lock();
try {
init();
} finally{ w.unlock(); }}/** * cache initialization, subclass implementation */
protected abstract void init(a);
}
Copy the code
II, CacheKey. Java
public class CacheKey {
public static final Integer CERTIFICATE_TYPE = 1001;
public static final Integer INDUSTRY = 1002;
}
Copy the code
III, CacheManager. Java
import java.util.Hashtable;
import java.util.Map;
/ * * *@ClassName CacheManager
* @DescriptionCache management@AuthorSonorous leaf *@Date 2019/10/6 11:11
* @Version1.0 * * * / javashizhan.com
public class CacheManager<K.V> {
private Map<Integer, Cache<K, V>> cacheMap = new Hashtable<Integer, Cache<K, V>>();
/** Private constructor */
private CacheManager(a) {}
private static volatile CacheManager cacheManager;
/** * singleton mode *@return* /
public static CacheManager getInstance(a) {
if (null == cacheManager) {
synchronized (CacheManager.class) {
if (null == cacheManager) {
cacheManager = newCacheManager(); }}}return cacheManager;
}
/** * Register cache *@paramCacheKey cacheKey *@param cache
*/
public void registerCache(Integer cacheKey, Cache<K, V> cache) {
cache._init();
cacheMap.put(cacheKey, cache);
}
/** * Retrieves data from the specified cache *@paramCacheKey cacheKey *@param key
* @return* /
public V getValue(Integer cacheKey, K key) {
Cache<K, V> cache = cacheMap.get(cacheKey);
return cache.get(key);
}
/** * set the cache *@paramCacheKey cacheKey *@param key
* @param value
*/
public void put(Integer cacheKey, K key, V value) {
Cache<K, V> cache = cacheMap.get(cacheKey);
cache.put(key, value);
}
/** * Removes data from the specified cache *@paramCacheKey cacheKey *@param key
*/
public V remove(Integer cacheKey, K key) {
Cache<K, V> cache = cacheMap.get(cacheKey);
returncache.remove(key); }}Copy the code
IV, IndustryCache. Java
/ * * *@ClassName IndustryCache
* @DescriptionIndustry Caching@AuthorSonorous leaf *@Date2019/10/6 though *@Version1.0 * * * / javashizhan.com
public class IndustryCache extends Cache {
/** * Initializes the cache, which can be self-implemented, such as reading data from a database */
@Override
public void init(a) {
put("01"."Building materials");
put("."."Metallurgical minerals");
put("3"."Petrochemical");
put("04"."Water and hydropower"); }}Copy the code
V, CertificateTypeCache. Java
/ * * *@ClassName CertificateTypeCache
* @DescriptionDocument type cache *@AuthorSonorous leaf *@Date 2019/10/6 11:32
* @Version1.0 * * * / javashizhan.com
public class CertificateTypeCache extends Cache {
/** * Initializes the cache, which can be self-implemented, such as reading data from a database */
@Override
public void init(a) {
put("01"."Identity card");
put("."."Passport");
put("3"."Military badge");
put("04".Student ID Card); }}Copy the code
VI. Use examples
public class CacheTest {
public static void main(String[] args) {
// Initialize the cache
Cache certificateTypeCache = new CertificateTypeCache();
Cache industryCache = new IndustryCache();
CacheManager.getInstance().registerCache(CacheKey.CERTIFICATE_TYPE, certificateTypeCache);
CacheManager.getInstance().registerCache(CacheKey.CERTIFICATE_TYPE, industryCache);
// Get the certificate type
Object value = CacheManager.getInstance().getValue(CacheKey.CERTIFICATE_TYPE,"01");
System.out.println("value: " + value);
// Add data to the id type cache
CacheManager.getInstance().put(CacheKey.CERTIFICATE_TYPE, "99"."Police officer's I.D.");
value = CacheManager.getInstance().getValue(CacheKey.CERTIFICATE_TYPE,"99");
System.out.println("value: " + value);
// The id type cache removes data
CacheManager.getInstance().remove(CacheKey.CERTIFICATE_TYPE, "99");
value = CacheManager.getInstance().getValue(CacheKey.CERTIFICATE_TYPE,"99");
System.out.println("value: "+ value); }}Copy the code
Output log:
Value: building materials value: police certificate value: nullCopy the code
Cache initialization and registration
1. The cache initialization mode can be lazy loading or diligent loading as required.
2. In Spring, diligent loading can be done during the Spring initialization process, for example, in the startup class, another better way is to load and register each cache class by itself, the code reference is as follows:
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/ * * *@ClassName IndustryCache
* @Description TODO
* @AuthorSonorous leaf *@Date 2019/10/6 13:08
* @Version1.0 * * * / javashizhan.com
@Component
public class IndustryCache extends Cache {
/** * can be self-implemented, such as reading data from a database */
@Override
public void init(a) {
put("01"."Building materials");
put("."."Metallurgical minerals");
put("3"."Petrochemical");
put("04"."Water and hydropower");
}
@PostConstruct
public void register(a) {
CacheManager.getInstance().registerCache(CacheKey.INDUSTRY, this); }}Copy the code
1. The first step is to add the @Component annotation to each cache class so that it will be loaded into memory when Spring starts.
2. Implement a cache registration method in each cache class and add @postConstruct annotation so that this method will be called automatically after spring instantiates the cache class.
The initialization and registration of each cache is then all about itself, enabling separation of responsibilities, cohesion, and decoupling.
end.
<– Read the mark, left like!