当前位置:网站首页>[hand tearing code] single case mode and producer / consumer mode
[hand tearing code] single case mode and producer / consumer mode
2022-07-06 13:37:00 【Li bohuan】
The singleton pattern
The singleton pattern (Singleton Pattern): Ensure that a class has only one object , And provide a global access point to access it .
Advantages of singleton mode :
Because the singleton mode only generates one instance , Reduced system performance overhead , When more resources are needed to generate an object , Such as read configuration 、 When other dependent objects are generated , You can start... In the application Directly generate a singleton object , Then permanent resident memory to solve
The singleton mode can set the global access point in the system , Optimize ring shared resource access , For example, you can design A singleton class , Responsible for the mapping of all data tables
Code implementation :
Hungry Chinese style : Create before use , Thread safety , Take up memory .
public class SingleClassA {
//1. Privatized construction method , So that this method cannot be called outside the class , Limit the generation of multiple objects
private SingleClassA(){ }
//2. Create an instance of the class inside the class
// Class initialization , Load this object now ( There is no advantage of delayed loading ). When loading a class , Naturally, it's thread safe !
private static final SingleClassA instance = new SingleClassA();
//3. Call methods to external providers : Return the created object to , Can only be called through a class
// Method is not synchronized , High call efficiency !
public static SingleClassA getInstance(){
return instance;
}
public static void main(String[] args) {
SingleClassA a = getInstance();
SingleClassA b = getInstance();
System.out.println(a == b);
}
}
Output results :
Slacker type : Created when used , Thread unsafe ( When creating or getting a singleton object ), Locking will affect efficiency .
public class SingleClassB {
//1. Privatized construction method , So that this method cannot be called outside the class , Limit the generation of multiple objects
private SingleClassB(){ }
//2. Create an instance of the class inside the class
private static SingleClassB instance ;
//3. Call methods to external providers : Return the created object to , Can only be called through a class
public static synchronized SingleClassB getInstance(){
if(instance == null) {
instance = new SingleClassB();
}
return instance;
}
// test
public static void main(String[] args) {
SingleClassB a = SingleClassB.getInstance();
SingleClassB b = SingleClassB.getInstance();
System.out.println(a==b);
}
}
Output results :
The difference between lazy man mode and hungry man mode :
- Lazy style will not instantiate by default , Wait until the method is called externally before , The object is instantiated in the hungry class loading stage
- Thread safe , Hungry man style must be thread safe , Because the object was instantiated before the thread appeared , Lazy is thread unsafe , Because in multithreading , If a thread judges that the finished instance is null Sleep or interrupt , Then another thread also enters the method , The judgment example is also null, Then the thread will create an instance object , After the original dormant thread resumes , Execute instantiation directly new Object step , Then there will be multiple instances .
- Analyze the thread safety above , Next is performance , Maybe you already have , The hungry man style doesn't need to be locked , High execution efficiency , Lazy style needs to be locked , Inefficient execution
- Occupy memory , Hungry man style whether you use its instance object or not , He was instantiated there from the beginning , Occupy memory space , The lazy type is instantiated only when it is used , It doesn't waste memory
producer / Consumer model
The producer-consumer pattern solves the problem of strong coupling between producer and consumer through a container . Producers and consumers do not communicate directly with each other , Instead, it communicates by blocking the queue , So producers don't have to wait for consumers to process their data , Throw it directly into the blocking queue , Consumers don't ask producers for data , I'm going to take it directly from the blocking queue , Blocking a queue is like a buffer , Balancing the processing power of producers and consumers . As shown in the figure below :
Code implementation :
@Slf4j(topic = "ProductAndConsumer")
public class ProductAndConsumer {
public static void main(String[] args) {
MessageQueue messageQueue = new MessageQueue(2);
// 3 Producer threads
for (int i = 0; i < 3; i++) {
int id = i;
new Thread(() -> {
messageQueue.put(new Message(id, " value " + id));
}, " producer " + i).start();
}
// 1 Consumer threads , Processing results
new Thread(() -> {
while (true) {
try {
sleep(1000);
Message message = messageQueue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, " consumer ").start();
}
}
final class Message {
private int id;
private Object message;
public Message(int id, Object message) {
this.id = id;
this.message = message;
}
public int getId() {
return id;
}
public Object getMessage() {
return message;
}
@Override
public String toString() {
return "Message{" +
"id=" + id +
", message=" + message +
'}';
}
}
@Slf4j(topic = "MessageQueue")
class MessageQueue {
private LinkedList<Message> queue;
private int capacity;
public MessageQueue(int capacity) {
this.capacity = capacity;
queue = new LinkedList<>();
}
public Message take() {
synchronized (queue) {
while (queue.isEmpty()) {
log.debug(" The queue is empty , Consumer thread waiting ");
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Message message = queue.removeFirst();
log.debug(" Consumed news {}",message);
queue.notifyAll();
return message;
}
}
public void put(Message message) {
synchronized (queue) {
while (queue.size() == capacity) {
try {
log.debug(" Inventory has reached the upper limit , Producer thread waiting ");
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.addLast(message);
log.debug(" The message has been produced {}",message);
queue.notifyAll();
}
}
}
The output is as follows :
边栏推荐
- 魏牌:产品叫好声一片,但为何销量还是受挫
- The overseas sales of Xiaomi mobile phones are nearly 140million, which may explain why Xiaomi ov doesn't need Hongmeng
- [the Nine Yang Manual] 2016 Fudan University Applied Statistics real problem + analysis
- Questions and answers of "basic experiment" in the first semester of the 22nd academic year of Xi'an University of Electronic Science and technology
- 4. Binary search
- ABA问题遇到过吗,详细说以下,如何避免ABA问题
- 【毕业季·进击的技术er】再见了,我的学生时代
- 仿牛客技术博客项目常见问题及解答(三)
- 关于双亲委派机制和类加载的过程
- View UI Plus 发布 1.3.1 版本,增强 TypeScript 使用体验
猜你喜欢
1. C language matrix addition and subtraction method
西安电子科技大学22学年上学期《信号与系统》试题及答案
Summary of multiple choice questions in the 2022 database of tyut Taiyuan University of Technology
编写程序,模拟现实生活中的交通信号灯。
C语言入门指南
仿牛客技术博客项目常见问题及解答(三)
Quickly generate illustrations
魏牌:产品叫好声一片,但为何销量还是受挫
3.输入和输出函数(printf、scanf、getchar和putchar)
6.函数的递归
随机推荐
【毕业季·进击的技术er】再见了,我的学生时代
Design a key value cache to save the results of the most recent Web server queries
优先队列PriorityQueue (大根堆/小根堆/TopK问题)
Wei Pai: the product is applauded, but why is the sales volume still frustrated
关于双亲委派机制和类加载的过程
凡人修仙学指针-2
Redis cache obsolescence strategy
9.指针(上)
C language Getting Started Guide
甲、乙机之间采用方式 1 双向串行通信,具体要求如下: (1)甲机的 k1 按键可通过串行口控制乙机的 LEDI 点亮、LED2 灭,甲机的 k2 按键控制 乙机的 LED1
【九阳神功】2016复旦大学应用统计真题+解析
IPv6 experiment
为什么要使用Redis
C语言实现扫雷游戏(完整版)
学编程的八大电脑操作,总有一款你不会
【话题终结者】
Relational algebra of tyut Taiyuan University of technology 2022 database
Data manipulation language (DML)
Redis的两种持久化机制RDB和AOF的原理和优缺点
Cloud native trend in 2022