Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrency and reusage of org.w3c.dom.Node

From here I learned that org.w3c.dom.Node (and other classes in the same package) are not thread-safe.

I am asking myself if and how should I cache those classes?

  • Is there a best approach?
  • Do immutable wrapper classes exist?
  • Should I use a ThreadLocal for the DocumentBuilder/DocumentBuilderFactory instead
    and recreate the Node everytime?
  • What do you do?
like image 488
MRalwasser Avatar asked Nov 04 '22 00:11

MRalwasser


2 Answers

You don't want to cache the XML document. It would be better to read/parse it into a "configuration" object. Depending on how complex or simple your configuration is, it could be a simple Map or something more complex.

One benefit (beyond the concurrency problems from parsing the same doc from multiple threads) is that you are not tied to the XML format for your configuration. Think about how all configs used to be in properties files, then XML came about and every open source package added support for XML. Then annotations came, and that was supported then too. Hibernate is a good example of that.

What you want to do is parse your config file and keep the resulting configuration object in your cache instead of the source XML.

like image 73
mprivat Avatar answered Nov 09 '22 07:11

mprivat


your only choice is to synchronize all access to the Document/Nodes. if it is well encapsulated (the DOM objects are maintained by a single class and all DOM manipulation is within that class) then you can just synchronized that entry point class. if the Nodes are passed around among other objects, then you have major problems. you would basically need to decide on a single object which would be your "lock" class and synchronize on it around all access to the config file Nodes.

like image 32
jtahlborn Avatar answered Nov 09 '22 06:11

jtahlborn