I work with the OpenSource OODB db4o and my serialized classes inherit from a common abstract.class which have two fields :
. . .
private final Long timeCreate = (System.currentTimeMillis() << 20) + (System.nanoTime() & 0xfffff);
private final int hashCode = timeCreate.hashCode();
. . .
@Override
public final int hashCode() {
return hashCode;
}
. . .
Is it a good practice to so?
The benchmarks I’ve tried give faster responses, but is a pitfall nested some where?
Ideally a hashCode of an object shouldn’t change in any case. One option is to only generate it on demand but in your case you have the problem that the timeCreate is not sure to be unique or monotonically increasing. System.nanoTime() can produce the same value over 1000 times if you only have micro-second resolution.
Note: if two objects are equals == true, they must have the same hashCode.