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;
    }
}
相关推荐
栈与堆20 分钟前
LeetCode-1-两数之和
java·数据结构·后端·python·算法·leetcode·rust
superman超哥27 分钟前
双端迭代器(DoubleEndedIterator):Rust双向遍历的优雅实现
开发语言·后端·rust·双端迭代器·rust双向遍历
1二山似32 分钟前
crmeb多商户启动swoole时报‘加密文件丢失’
后端·swoole
马卡巴卡33 分钟前
Java CompletableFuture 接口与原理详解
后端
神奇小汤圆42 分钟前
Java线程协作工具:CountDownLatch 、CyclicBarrier、Phaser、Semaphore 、Exchanger
后端
gelald1 小时前
ReentrantLock 学习笔记
java·后端
计算机学姐1 小时前
基于SpringBoot的校园资源共享系统【个性化推荐算法+数据可视化统计】
java·vue.js·spring boot·后端·mysql·spring·信息可视化
J_liaty1 小时前
RabbitMQ面试题终极指南
开发语言·后端·面试·rabbitmq
福大大架构师每日一题1 小时前
2026年1月TIOBE编程语言排行榜,Go语言排名第16,Rust语言排名13。C# 当选 2025 年度编程语言。
golang·rust·c#
BD_Marathon2 小时前
SpringBoot程序快速启动
java·spring boot·后端