1

当我阅读play framework 1.2.5的源码时,我发现了这个类:

package play.classloading;

import java.util.concurrent.atomic.AtomicLong;

/**
 * Each unique instance of this class represent a State of the ApplicationClassloader.
 * When some classes is reloaded, them the ApplicationClassloader get a new state.
 * <p/>
 * This makes it easy for other parts of Play to cache stuff based on the
 * the current State of the ApplicationClassloader..
 * <p/>
 * They can store the reference to the current state, then later, before reading from cache,
 * they could check if the state of the ApplicationClassloader has changed..
 */
public class ApplicationClassloaderState {
    private static AtomicLong nextStateValue = new AtomicLong();

    private final long currentStateValue = nextStateValue.getAndIncrement();

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        ApplicationClassloaderState that = (ApplicationClassloaderState) o;

        if (currentStateValue != that.currentStateValue) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return (int) (currentStateValue ^ (currentStateValue >>> 32));
    }
}

我不明白这个hashCode方法,为什么它使用这个实现:

return (int) (currentStateValue ^ (currentStateValue >>> 32));

源码网址: https ://github.com/playframework/play/blob/master/framework/src/play/classloading/ApplicationClassloaderState.java#L34

4

1 回答 1

0

hashCode() 必须按设计返回一个 int。currentStateValue 是一个长数字,表示 ApplicationClassloader 的内部状态变化。表演!framework 是一个复杂的 Web 框架,具有所谓的热代码替换和重新加载功能。此功能实现的核心部分是 play.classloading.ApplicationClassloader.detectChanges()。如您所见,有很多“新 ApplicationClassloaderState()”调用,这意味着(快速 - 取决于您的开发工作流程和应用程序大小)增加返回对象中的 currentStateValue 成员。

回到问题:实现的目标应该是保持最大的信息,以区分至少 2 个不同的状态。

尝试将 currentStateValue 理解为加密自身的(加密)密钥(用密码学术语来说是一种糟糕的方法),但在这种情况下它非常有用。也许你认识到这种关系。抱歉,我无法在此处发布链接,但您可以在维基百科中找到一些有用的提示,搜索“Involution_%28mathematics%29”、“One-time_pad”、“Tabula_recta”。

于 2014-01-22T00:06:30.470 回答