【问题标题】:Spring: how to make thread-safe @Component?Spring:如何制作线程安全的@Component?
【发布时间】:2015-12-24 07:39:18
【问题描述】:

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

@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
}

我是 Spring Boot 的新手,我知道 Spring Security,但我想做自己的安全服务。有什么方法可以让我的 @Component 类使用 Spring Boot 线程安全?

【问题讨论】:

  • 为什么要将令牌存储在内存中?你没有数据库吗?不管怎样,你在 Spring boot 中创建一个线程安全的类,就像在任何其他环境中一样:通过使用线程安全类和/或同步访问共享状态。

标签: java multithreading spring spring-boot


【解决方案1】:

您只需要使您的设置线程安全。您可以使用 ConcurrentSkipListSet 代替 HashSet 来使其成为线程安全的。

【讨论】:

  • 感谢您的回复!但是我可以安全地修改这个集合中的数据吗?
  • 你可以使用同步的Hashtable
  • Big No no... 与 ConcurrentSkipListSet 相比,HashTable 的性能会很差。每个方法都是HashTable同步的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-06
  • 2012-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-24
相关资源
最近更新 更多