小编jor*_*own的帖子

如何禁用Guava缓存?

JavaCachingWithGuava建议关闭缓存的规范方法是设置maximumSize = 0.但是,我希望下面的测试通过:

public class LoadingCacheTest {
    private static final Logger LOG = LoggerFactory.getLogger(LoadingCacheTest.class);

    LoadingCache<String, Long> underTest;

    @Before
    public void setup() throws Exception {
        underTest = CacheBuilder.from("maximumSize=0").newBuilder()
                .recordStats()
                .removalListener(new RemovalListener<String, Long>() {
                    @Override
                    public void onRemoval(RemovalNotification<String, Long> removalNotification) {
                        LOG.info(String.format("%s cached value %s for key %s is evicted.", removalNotification.getCause().name(), removalNotification.getValue(), removalNotification.getKey()));
                    }
                })
                .build(new CacheLoader<String, Long>() {
                    private final AtomicLong al = new AtomicLong(0);
                    @Override
                    public Long load(@NotNull final String key) throws Exception {
                        LOG.info(String.format("Cache miss for …
Run Code Online (Sandbox Code Playgroud)

java guava

3
推荐指数
1
解决办法
2167
查看次数

非阻塞算法生成唯一的负数

我最近重构了一段用于生成唯一负数的代码.
编辑:多个线程获取这些ID并将其作为键添加到DB; 数字必须是负数才能轻易识别 - 在测试会话结束时,它们将从数据库中删除.

我的Java算法如下所示:

private final Set<Integer> seen = Collections.synchronizedSet(new HashSet<Integer>());
public Integer generateUniqueNegativeIds() {
    int result = 0;
    do {
        result = random.nextInt();
        if (result > 0) {
            result *= -1;
        }
    } while (!seen.add(result));
    return result;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码结构,以及对set和"retry"循环的推测性添加,使我认为有一个等效的非阻塞算法用任何原子变量替换同步集.

我做了一些尝试使用原子变量重写,但都失败了多线程攻击测试.

是否有优雅的非阻塞等价物?

编辑:为了好奇,这里是一个使用原子整数作为守卫的有缺陷的尝试

private final AtomicInteger atomi = new AtomicInteger(0);
public Integer generateUniqueNegativeIdsWithAtomicAlgo() {
    boolean added = false;
    int result = 0;
    do {
        result = random.nextInt();
        if (result > 0) {
            result *= …
Run Code Online (Sandbox Code Playgroud)

java algorithm atomic nonblocking

2
推荐指数
2
解决办法
1234
查看次数

标签 统计

java ×2

algorithm ×1

atomic ×1

guava ×1

nonblocking ×1