go 系列之 once

一、简介

once 方法用于保证指定函数只执行一次。例如配置懒加载,客户端获取密钥等场景,都可以用到once。

二、技术实现

2.1 Once.go
Go 复制代码
type Once struct {
	done atomic.Uint32
	m    Mutex
}


func (o *Once) Do(f func()) {

	if o.done.Load() == 0 {
		
		o.doSlow(f)
	}
}

func (o *Once) doSlow(f func()) {
	o.m.Lock()
	defer o.m.Unlock()
	if o.done.Load() == 0 {
		defer o.done.Store(1)
		f()
	}
}
Go 复制代码
type DemoClient struct {
	secretKey string
	once      sync.Once
}

func (c *DemoClient) getSecretKey() string {
    c.once.Do(func() {
		c.secretKey = string(rand.Int63())
	})
	return c.secretKey
}
2.2 Once.java
java 复制代码
public class Once {
    private volatile  boolean done = false;

    private Runnable func;

    public Once(Runnable func) {
        this.func = func;
    }

    public void exec(){
        if (done){
            return;
        }
        synchronized (this){
            if (!done){
                func.run();
                done = true;
            }
        }
    }
}
java 复制代码
/**
* 使用样例
*/
public class DemoClient {
    private String secretKey;
    
    private Once once = new Once(()->{
        secretKey = RandUtil.randAlpha(32);
    });
    
    public String getSecretKey(){
        once.exec();
        return secretKey;
    }
}
相关推荐
IT_陈寒6 小时前
7个鲜为人知的JavaScript性能优化技巧,让你的网页加载速度提升50%
前端·人工智能·后端
几颗流星6 小时前
Rust 常用语法速记 - 迭代器
后端·rust
清空mega7 小时前
从零开始搭建 flask 博客实验(4)
后端·python·flask
bcbnb7 小时前
iPhone HTTPS 抓包,从无法抓包到定位问题的流程(Charles/tcpdump/Wireshark/Sniffmaster)
后端
Data_Adventure7 小时前
TypeScript 开发者转向 Java:学习重点与思维迁移指南
后端
吴祖贤7 小时前
Spring AI 零基础入门:从踩坑到上手的完整指南
后端
code_std7 小时前
SpringBoot 登录验证码
java·spring boot·后端
Mos_x8 小时前
@RestController注解
java·后端
bcbnb8 小时前
Fiddler抓包工具使用教程,HTTPHTTPS抓包、代理配置与调试技巧全解析(附实战经验)
后端