go 系列之 once

一、简介

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

二、技术实现

2.1 Once.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()
	}
}
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
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;
            }
        }
    }
}
/**
* 使用样例
*/
public class DemoClient {
    private String secretKey;
    
    private Once once = new Once(()->{
        secretKey = RandUtil.randAlpha(32);
    });
    
    public String getSecretKey(){
        once.exec();
        return secretKey;
    }
}

你可能感兴趣的:(golang,后端)