作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想制作一个应该包含访问 token 的 Token
类。但是,一旦 token 在下次使用时过期,则应刷新 token 。问题是这需要以线程安全的方式处理。只要 isExpired
为假,每个人都应该能够访问 token 。但是一旦 token 过期,只应进行一次更新 token 的调用,而其他试图读取 token 的调用则必须等待。
到目前为止,我有以下内容:
public class Token {
private boolean isExpired = true;
private String token = "";
private final AccessTokenClient tokenRetriever;
public Token(AccessTokenClient tokenRetriever) {
this.tokenRetriever = tokenRetriever;
}
public String getToken() {
// If isExpired true
// Use tokenRetriever to get a new token
// Only one request to getToken should try to update the token, others trying to call getToken has to wait.
return null;
}
}
我的问题是:在 Java 8 中实现这样的访问 token 缓存的惯用方法是什么?
最佳答案
这是我能想到的最基本的例子:
public class Token {
private final AccessTokenClient tokenRetriever;
private final Object monitor;
private volatile boolean isExpired = true;
private volatile String token = "";
public Token(AccessTokenClient tokenRetriever) {
this.tokenRetriever = tokenRetriever;
this.monitor = new Object();
}
public String getToken() {
if (this.isExpired) {
synchronized (this.monitor) {
// intended double check!
if (this.isExpired) {
this.token = this.tokenRetriever.retrieveToken();
this.isExpired = false;
}
}
}
return this.token;
}
}
关于java - 用于在 Java 中保存访问 token 的线程安全类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56495189/
我是一名优秀的程序员,十分优秀!