Java Spring:如何使线程安全@Component?

Java Spring:如何使线程安全@Component?,java,multithreading,spring,spring-boot,Java,Multithreading,Spring,Spring Boot,我尝试为REST服务创建自己的基于令牌的授权。这是我的代币服务: @Component public class TokenService { ... private Set<Token> tokens; private SecureRandom random; ... public TokenService() { this.tokens = new HashSet<Token>(); this.r

我尝试为REST服务创建自己的基于令牌的授权。这是我的代币服务:

@Component
public class TokenService {
    ...
    private Set<Token> tokens;
    private SecureRandom random;
    ...
    public TokenService() {
        this.tokens = new HashSet<Token>();
        this.random = new SecureRandom();
    }
    public boolean has(final String token) {
        clear();

        Token tokenStub = new Token(token);
        return this.tokens.contains(tokenStub);
    }
    public boolean remove(final String token) {
        Token tokenStub = new Token(token);
        return this.tokens.remove(tokenStub);
    }
    public Token retrieve(final TokenDetails tokenDetails) {
        clear();

        Token token = this.get(tokenDetails);
        if (token == null) {
            return gen(tokenDetails);
        }

        token.setDate(System.currentTimeMillis());
        token.setTokenDetails(tokenDetails);

        return token;
    }
    ... //other methods
}
@组件
公共类令牌服务{
...
私设代币;
私有安全随机;
...
公共代币服务(){
this.tokens=new HashSet();
this.random=新的SecureRandom();
}
公共布尔has(最终字符串标记){
清除();
令牌存根=新令牌(令牌);
返回this.tokens.contains(tokenStub);
}
公共布尔删除(最终字符串标记){
令牌存根=新令牌(令牌);
返回此.tokens.remove(tokenStub);
}
公共令牌检索(最终令牌详细信息令牌详细信息){
清除();
Token Token=this.get(tokenDetails);
if(标记==null){
返回gen(令牌详细信息);
}
token.setDate(System.currentTimeMillis());
token.setTokenDetails(tokenDetails);
返回令牌;
}
…//其他方法
}

我是SpringBoot的新手,我知道SpringSecurity,但我想做我自己的安全服务。有没有办法让我的@Component类使用Spring Boot线程安全?

你只需要让你的设置线程安全。您可以使用而不是HashSet使其线程安全。

您只需使您的集线程安全即可。您可以使用而不是HashSet使其线程安全。

为什么要在内存中存储令牌?你没有数据库吗?无论如何,您在Spring boot中使类成为线程安全的,与在任何其他环境中一样:通过使用线程安全类和/或同步对共享状态的访问。为什么要在内存中存储令牌?你没有数据库吗?无论如何,您在Spring boot中使用线程安全类的方式与在任何其他环境中使用线程安全类的方式相同:使用线程安全类和/或同步对共享状态的访问。谢谢您的回复!但是我可以安全地修改这个集合中的数据吗?您可以使用同步的哈希表big No。。。与ConcurrentSkipListSet相比,哈希表性能较差。每个方法都是哈希表同步的,谢谢回复!但是我可以安全地修改这个集合中的数据吗?您可以使用同步的哈希表big No。。。与ConcurrentSkipListSet相比,哈希表性能较差。每个方法都与哈希表同步。