当前位置:网站首页>Singleton mode application
Singleton mode application
2022-06-25 17:02:00 【Four questions and four unknowns】
preface
We know a lot about singleton mode , The previous article also briefly described a single instance mode ( link :https://blog.csdn.net/zkkzpp258/article/details/111667568), Because in the text :https://www.runoob.com/design-pattern/singleton-pattern.html The website is very detailed, so I won't go into details , Let's talk more about application , After all, learning these design patterns is to apply them to practice .
After my personal comparison , In my opinion, the following two kinds of better singleton pattern design methods :
- Implement the singleton through the static inner class . The static member variables of a static inner class will only be initialized once during initialization .
- Singleton is realized by enumeration .
Singleton of static inner class implementation
The following is an example of a static inner class implementation .
package com.hust.zhang.singleton;
public class HolderSingleton {
public HolderSingleton() {
}
static class Holder {
private static final HolderSingleton instance = new HolderSingleton();
}
public static final HolderSingleton getInstance() {
return Holder.instance;
}
}Enumerate the singletons of the implementation
Let's take a look at the single example implemented by enumeration , Enumeration types are actually Java The compiler converts to a corresponding class , This class inherits Java API Medium java.lang.Enum class
public enum EnumSingleton {
INSTANCE;
EnumSingleton() {
System.out.println("instance will be initialized immediately");
}
public static EnumSingleton getInstance() {
return INSTANCE;
}
}The following singleton is implemented by enumerating to create a thread pool ,
package com.hust.zhang.threadpool;
import jodd.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.*;
@Slf4j
public enum ThreadPool {
INSTANCE;
private static final ThreadPoolExecutor THREAD_POOL_EXECUTOR;
// Number of core threads
private static final int corePoolSize = 10;
// Maximum number of threads
private static final int maxPoolSize = 30;
// Work queue size
private static final int workQueueCapacity = 20;
// Idle thread lifetime
private static final long keepAliveTime = 30000L;
static {
THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(corePoolSize,
maxPoolSize,
keepAliveTime,
TimeUnit.MICROSECONDS,
new LinkedBlockingQueue<>(workQueueCapacity),
// Use the chain method to create ThreadFactory
new ThreadFactoryBuilder().setNameFormat("my_definition_pool_").get(),
CallerRunsPolicy Refusal strategy : After the task is rejected and added to the queue , Can use call execute Function to execute the rejected task .
new ThreadPoolExecutor.CallerRunsPolicy()) {
/**
* Handle thread pool exception information
*
* @param runnable
* @param throwable
*/
@Override
protected void afterExecute(Runnable runnable, Throwable throwable) {
super.afterExecute(runnable, throwable);
if (throwable == null && runnable instanceof Future<?>) {
try {
((Future<?>) runnable).get();
} catch (CancellationException ce) {
log.error("thread pool cancellation exception");
} catch (ExecutionException ee) {
log.error("thread pool execution exception");
} catch (InterruptedException ie) {
log.error("thread pool interrupted exception");
Thread.currentThread().interrupt();
}
if (throwable != null) {
log.error("thread pool exception");
}
}
}
};
// Allow core threads to recycle
THREAD_POOL_EXECUTOR.allowCoreThreadTimeOut(true);
}
public ThreadPoolExecutor getInstance() {
return THREAD_POOL_EXECUTOR;
}
}The test class is as follows ,
package com.hust.zhang;
import com.alibaba.fastjson.JSON;
import com.hust.zhang.threadpool.ThreadPool;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
@Slf4j
public class ThreadPoolTest {
static class ThreadProcess implements Runnable {
private int threadId;
private CountDownLatch countDownLatch;
ThreadProcess(int threadId, CountDownLatch countDownLatch) {
this.threadId = threadId;
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
try {
MDC.put("threadId", String.valueOf(threadId));
} finally {
countDownLatch.countDown();
}
}
}
public static void main(String[] args) {
// adopt ThreadPool Enumerate to get the thread pool with parameters in the instance
ThreadPoolExecutor threadPool = ThreadPool.INSTANCE.getInstance();
int threadNum = 5;
CountDownLatch countDownLatch = new CountDownLatch(threadNum);
for (int i = 0; i < threadNum; i++) {
int threadId = i;
log.info("threadPool parameter:= {}", JSON.toJSONString(threadPool));
threadPool.submit(new ThreadProcess(threadId, countDownLatch));
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
log.info("throw InterruptedException");
}
System.out.println("mission accomplished!");
}
}among MDC It can be used to log threads , It is convenient to pass in the log grep The command traces the thread that processes the log .MDC adopt MDCAdapter To achieve , There are many adapters (BasicMDCAdapter、Log4jMDCAdapter、LogbackMDCAdapter、NOPMDCAdapter), Mainly by maintaining a Map Save the variables bound to the thread (ThreadLocal).
The above is about putting a limited number of tasks into the thread pool , What should I do if there are infinite threads ? Next, for the possible infinite tasks, put them in the queue , Start a thread loop to determine whether the queue is empty , If it is not empty, put the task into the thread pool .
package com.hust.zhang;
import com.hust.zhang.threadpool.ThreadPool;
import lombok.extern.slf4j.Slf4j;
import java.util.Arrays;
import java.util.Deque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Slf4j
public class ThreadPoolTest2 {
static class ThreadProcess implements Runnable {
private Deque deque;
ThreadProcess(Deque deque) {
this.deque = deque;
}
@Override
public void run() {
try {
Object value = deque.peek();
log.info("the task is running ... task value = {}", value);
} finally {
deque.poll();
}
}
}
public static void main(String[] args) {
Deque deque = MyLinkedDeque.getInstance();
ThreadPoolExecutor poolExecutor = ThreadPool.INSTANCE.getInstance();
poolExecutor.submit(() -> {
while (true) {
if (!deque.isEmpty()) {
poolExecutor.submit(new ThreadProcess(deque));
} else {
log.info("ConcurrentLinkedDeque is empty ...");
}
TimeUnit.SECONDS.sleep(1);
}
});
// Start a thread every 5 Add three tasks to the queue in seconds
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
TimeUnit.SECONDS.sleep(5);
Arrays.asList("task1","task2",123).stream().forEach(value -> deque.add(value));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
The output effect is as follows ,
summary
It is not good to create a thread pool in this way , You can also create directly in the class ThreadPoolExecutor With online process pool parameters , It's just that it's easier to write a customized thread pool and call it yourself , Your own business processing class should also be clean .
Someone might be thinking , If different businesses in a microservice share the same thread pool, will they affect each other , Do you want to create more than just a thread pool singleton , In fact, create multiple thread pools to manage them separately , In essence, computers are also mutually preemptive of resources , So the difference is not that big .
In addition , Although the previous article also mentioned , The Alibaba development manual mandates that you do not use Executors To create a thread pool, use ThreadPoolExecutor How to create , This is to make the running rules of the thread pool more clear , Avoid the risk of resource depletion .
FixedThreadPool and SingleThreadPool: The allowed request queue length is Integer.MAX_VALUE, A large number of requests may pile up , Which leads to OOM.
CachedThreadPool and ScheduledThreadPool: The number of threads allowed to be created is Integer.MAX_VALUE, A large number of threads may be created , Which leads to OOM.
边栏推荐
- SMART PLC如何构造ALT指令
- Problems encountered in using MySQL
- SnakeYAML配置文件解析器
- Creating a uniapp project using hbuilder x
- 【機器學習】基於多元時間序列對高考預測分析案例
- 【蓝桥杯集训100题】scratch指令移动 蓝桥杯scratch比赛专项预测编程题 集训模拟练习题第14题
- STM32硬件错误HardFault_Handler的处理方法
- Differences between et al and etc
- PLSQL 存储函数SQL编程
- [Jianzhi offer II 091. painting the house]
猜你喜欢

解析数仓lazyagg查询重写优化

Paper notes: lbcf: a large scale budget constrained causal forest algorithm

STM32硬件错误HardFault_Handler的处理方法
![[Jianzhi offer II 091. painting the house]](/img/63/dc54c411b1a2f2b1d69b62edafde38.png)
[Jianzhi offer II 091. painting the house]

【微服务|Sentinel】流控规则概述|针对来源|流控模式详解<直接 关联 链路>

论文笔记:LBCF: A Large-Scale Budget-Constrained Causal Forest Algorithm

Day_ fifteen

【效率】又一款笔记神器开源了!

Mac PHP multi version management and swoole extension installation

2022-06-17 网工进阶(九)IS-IS-原理、NSAP、NET、区域划分、网络类型、开销值
随机推荐
pychrm的这些配置,你都知道吗?
揭秘GES超大规模图计算引擎HyG:图切分
Do you know all the configurations of pychrm?
巴比特 | 元宇宙每日荐读:三位手握“价值千万”藏品的玩家,揭秘数字藏品市场“三大套路”...
3. conditional probability and independence
【機器學習】基於多元時間序列對高考預測分析案例
这些老系统代码,是猪写的么?
微信公众号服务器配置
Day_ twelve
Structure de la mémoire JVM
[untitled]
App测试工具大全,收藏这篇就够了
tasklet api使用
A complete collection of APP testing tools. It's enough to collect this one
Mac PHP multi version management and swoole extension installation
[proficient in high concurrency] deeply understand the basics of assembly language
剑指 Offer 50. 第一个只出现一次的字符
"Podcast with relish" 386 Yuan Tang Hua Yuan Shi: who is not a "Mr. White character"?
Vscode plug-in self use
Optimization of lazyagg query rewriting in parsing data warehouse