I have a array of objects from which I am constructing an xml document using java like below -
Object[] arr = fetchData();
Document newDoc =DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element rootElement = newDoc.createElement("company");
for(int i=0;i<arr.length();i++)
{
Element staff = new Element("staff");
staff.setAttribute(new Attribute("id", i));
staff.addContent(new Element("firstname").setText(arr[i].getFirstName()));
staff.addContent(new Element("lastname").setText(arr[i].getLastName()));
staff.addContent(new Element("nickname").setText(arr[i].getNickName()));
staff.addContent(new Element("salary").setText(arr[i].getSalary()));
............
............
............
............
............
rootElement.appendChild(staff);
}
newDoc.appendChild(rootElement);
The xml generated will be of following form -
<company>
<staff id="1">
<firstname>Foo</firstname>
<lastname>Bar</lastname>
<nickname>FB</nickname>
<salary>999999</salary>
............
............
............
............
</staff>
......
......
</company>
Above solution is working fine for small size of arrays but when array size increases it takes long time to process because of sequential processing of above code. Is there any way to process construction of staff element parallel either by using java 8 Stream parallel processing or threads in java?
Updated solution using CompletableFuture :
Object[] arr = fetchData();
Document newDoc =DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element rootElement = newDoc.createElement("company");
List<CompletableFuture<Element>> futureElements = new ArrayList<>();
for (int x = 0; x < arr.length(); x++) {
Object e = arr[x];
CompletableFuture<Element> f = CompletableFuture.supplyAsync(() -> getElement(newDoc, e));
futureElements.add(f);
}
for (CompletableFuture<Element> e : futureElements)
rootElement.appendChild(e.get());
newDoc.appendChild(rootElement);
new Element, you are not using the standard DOM API. We can’t guess the thread safety of an unspecified non-standard library.DocumentBuilderFactory.newInstance()might return an arbitraryDocumentBuilderimplementation, there is no guaranty that it will be thread safe and even worse, the fact, that nodes are created through theDocumentinterface and keep being associated with a document, invites the implementors to maintain hidden data structures combining these artifacts, which are unlikely to be thread safe. If performance is a concern, you should ask yourself whether you really need aDocumentBuilderor if a lightweight code assembling an XMLStringwould work as well. The latter can be parallel…