简体   繁体   中英

What is the correct lifecycle of a DOM Node in Java?

I'm wondering about the correctness of the following code in terms of lifecycle management and memory management that results from it:

org.w3c.dom.Document document = // some document

// Some long-running loop
for (;;) {

  // This element has "document" as its owner. But it is never added as a child
  // element into the document. It can be GC'ed at the end of the loop
  Element abc = document.createElement("abc");
}

Such temporary elements (or DocumentFragment , etc.) may be used in extensive DOM manipulations quite often. In Xerces, which is Java's standard DOM implementation, the element holds a reference to the document, but the document is unaware of Element. This allows for the garbage collector to clean up those elements when their scope is cleared (ie at the end of the loop). But this is not documented explicitly as such in the API. On the other hand, I don't see any operation in the DOM API allowing for "unsetting" abc 's owner document.

My question is: Am I right in assuming that a DOM document may never keep references to the nodes it creates with createXXX() , regardless of the implementation? Or is there any implementation where the above might lead to a memory leak?

Perhaps you could have a look at several DOM implementations source base and see how they behave and draw some conclusions from that? Is the problem that you don't have control over the specific DOM implementation used at run-time of you application or the fact that the implementation can be changed by your application users and they often do change it?

But if there isn't specific contract defined in the javadoc of document.createXXX methods, I am afraid that there will be no sure bet on exact behavior. So the only option that I see to be absolutely sure about what the behavior is is to control the implementation of DOM and know its behavior...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM