我有一个 session 范围的 bean,它读取 View 的内容并存储 SelectItem 对象的 HashMap 。然后使用它们填充 XPage 上的组合框值。
代码工作正常,除了当我尝试在最内循环中回收 ViewEntry 对象时。如果该行被注释掉,我的 SelectItems 就会正常返回。如果该行未注释,则我的组合框为空。所以我想知道的是:
- 为什么会发生这种情况?
- 如何解决此问题并像优秀开发人员那样正确回收对象?
- 如果我无法显式回收该对象,对内存等有什么潜在影响?
代码(突出显示问题行并当前已注释掉):
public class comboBox extends HashMap<String, List<SelectItem>> implements Serializable {
private static final long serialVersionUID = 1L;
public comboBox() {
this.init();
}
private void init() {
Database database = null;
View vwData = null;
ViewNavigator navData = null;
try {
PrimeUser thisUser = (PrimeUser) resolveVariable(FacesContext.getCurrentInstance(), "PrimeUser");
String lang = thisUser.getLang();
database = getCurrentDatabase();
vwData = database.getView("DataLookup");
navData = vwData.createViewNavFromCategory(lang);
ViewEntry keyCat = navData.getFirst();
ViewEntry nextCat = null;
while (keyCat != null) {
String thisKey = (String) keyCat.getColumnValues().get(1);
List<SelectItem> options = new ArrayList<SelectItem>();
options.add(new SelectItem("Please select..."));
ViewEntry dataEntry = navData.getChild(keyCat);
ViewEntry nextChild = null;
while (dataEntry != null) {
nextChild = navData.getNextSibling();
Object optValue = dataEntry.getColumnValues().get(2);
String optLabel = (String) dataEntry.getColumnValues().get(3);
options.add(new SelectItem(optValue, optLabel));
// dataEntry.recycle(); //<---- PROBLEM HERE
dataEntry = nextChild;
}
this.put(thisKey, options);
nextCat = navData.getNextCategory();
keyCat.recycle();
keyCat = nextCat;
}
} catch (NotesException e) {
e.printStackTrace();
} finally {
try {
navData.recycle();
vwData.recycle();
database.recycle();
} catch (NotesException e) {
}
}
}
public List<SelectItem> get(String key) {
return this.get(key);
}
}
已解决:
解决方案非常简单(感谢 Sven Hasselbach 提醒我再次查看服务器日志输出)。更改很简单 - 交换此行:
nextCat = navData.getNextCategory();
为此:
nextCat = getNextSibling(keyCat);
虽然“getNextCategory”是ViewNavigator的一个方法并且没有任何参数;它只获取当前条目之后的下一个类别。如果当前条目已被回收(如上面的情况),那么显然当前条目为 null 并且该方法会引发异常。
“getNextSibling”有一个可选的 ViewEntry 参数,如果指定,它将覆盖指向当前 ViewEntry 的指针,否则它将使用该指针。
我责怪星期五。
最佳答案
首先查看您的服务器控制台:您是否在那里看到 NotesException?如果遇到异常,您的 put 将永远不会被执行,因此您的组合框将为空。
在回收对象之前,必须测试它是否为 null,并由 try/catch block 包围。有一些实现可以更轻松地回收 Notes 对象,例如这个http://openntf.org/XSnippets.nsf/snippet.xsp?id=recycleobject-helper-for-recycling-of-objects
有关回收的详细解释可以在这里找到:http://nathantfreeman.wordpress.com/2013/03/21/recycle-and-the-retail-experience/
关于java - 对 Domino 对象使用回收会导致 Bean 不返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15568390/