XPage Java Object Recycle in SSJS

2019-02-06 22:28发布

问题:

I have read this suggestion about recycle of Domino objects: What is the best way to recycle Domino objects in Java Beans

What is best practice if I have a datasource named document and in a function that is called several times this code exists:

var doc=document.getDocument(true)

and doing stuff to the backend document.

Before I exit the function should I recycle doc or is my backend document to the datasource recycled then ?

回答1:

This is an excellent question, because this is one of the only exceptions to the "recycle everything" principle (two other notable examples are that you should never recycle the current session or database). It's a bad idea to recycle the back end document for a data source, because the JSF lifecycle gets the same handle, and you'd be recycling it out from under Domino. The data source takes care of this for us, so there's no need to recycle it manually. On the other hand, if you get a handle on specific items (i.e. doc.getFirstItem("someFieldName"), or item values that are dates, you should recycle those objects, just not the document itself.

By far the most important scenario where it's crucial to recycle Java and SSJS objects is in view iteration, because every time you advance to the next entry or document, you're leaking a handle if you skip the recycle. In most other cases, recycling is still advisable, but closer to being optional, because it takes a long time for other operations to leak enough to cause problems. But if you're iterating a very large view, you can easily run out of handles in a single iteration if you forget to recycle.

One parting thought, however: I rarely see a situation where getting a handle on the back end document of a data source is the best approach, so I'd recommend revisiting your code to ensure that it's even necessary to obtain this handle to begin with. For instance, instead of document.getDocument(true).getItemValueString("someFieldName"), just call document.getValue("someFieldName"). The value returned should be identical, but it will run more efficiently, and you're not touching the back end document, so recycling isn't an issue. And it's less typing for every item access, which certainly adds up over time. Similarly, instead of document.getDocument(true).replaceItemValue("someFieldName", "newValue"), substitute document.setValue("someFieldName", "newValue").