如果我有一個像這樣的不可變類:
public class MathClass {
private final int x;
public MathClass(int x) {
this.x = x;
}
public int calculateSomething() {
return Math.sqrt(x);
}
}
jvm 是否在第一次呼叫時快取了 calculateSomething() 的結果?我在 MathClass 中有一個更復雜的計算。
uj5u.com熱心網友回復:
不,它沒有,只有物件存盤在快取中
您可以使用自己的快取解決方案,例如 Spring@Cacheable將方法結果存盤在快取中
uj5u.com熱心網友回復:
不,Java 通常不快取方法結果。
框架的一些方法可以做到這一點,但這是它們實作的一部分,例如Integer.valueOf(int).
cf JavaDoc:
此方法將始終快取 -128 到 127(含)范圍內的值,并可能快取此范圍之外的其他值。”
但是通過您的實作,您可以輕松實作“快取”:該類是不可變的,這意味著輸入不會改變,因此您可以輕松計算第一個請求的值并在后續回傳先前計算的值要求:
public class MathClass {
private final int x;
private transient boolean calculated = false;
private transient int preCalcSomething;
public MathClass(int x) {
this.x = x;
}
public int calculateSomething() {
if (!calculated) {
preCalcSomething = Math.sqrt(x);
calculated = true;
}
return preCalcSomething;
}
}
我在transient這里使用關鍵字來標記這兩個欄位不是“物件狀態”的一部分。不要忘記將它們排除在計算之外equals,hashCode也許還有其他依賴于狀態的方法!
如果您使用的是物件而不是原語,那么null如果該值不能成為快取操作的實際結果,我將用作“尚未計算”的指示符。
uj5u.com熱心網友回復:
您可以只計算一次,然后回傳之前計算的結果。
public class MathClass {
private final int x;
private final int result;
public MathClass(int x) {
this.x = x;
this.result = Math.sqrt(x);
}
public int calculateSomething() {
return result;
}
}
計算不會超過一次。這不是快取,但在您的場景中可以用作快取。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/517100.html
標籤:爪哇方法
上一篇:注入點有以下注解:@org.springframework.beans.factory.annotation.Autowired(required=true)
