I wrote some code using documents4j
library to convert some documents from .docx
to .pdf
.
I followed the examples in the documentation and the convertion works perfectly using MS-Word, but I notice that after all conversions complete and methods return, the java application result still running and it seems not to exit.
If I explicitly close the converter using execute()
and shutDown()
methods instead of schedule()
, the application exit, but I need this application run in concurrent mode, so I can't explicitly invoke shutDown()
otherwise I cause MS-Word exits and breaks some still opened documents.
What is the best way to use the converter to achieve these objectives? Has LocalConverter
got a method to check if there is a queue of documents to be converted? With this information I could invoke shutDown()
only with an empty queue and instantiate a new LocalConverter on the next converting request.
Thanks in advance for your replies!
Dan
I am the maintainer of documents4j.
You are right, the LocalConverter
does not currently await termination of the running conversions when it is shut down. I added a grace period that corresponds to the timeout for running conversions to finish which will be included in the next version of documents4j. I will release a new version once I have looked into a pending issue with escaping path in folders containing spaces.
In the mean time, I recommend you to implement something similar yourself. Every conversion emitts a Future
. Simply collect all the futures in a Set
and then call get
on each future in a thread. If all futures have returned (ie all conversions are complete), it is safe to shut down the local converter:
IConverter converter = ...;
Set<Future<?>> futures = new HashSet<>();
for ( ... ) {
futures.add(converter.from(...).to(...).schedule());
}
for (Future<?> future : futures) {
future.get();
}
converter.shutDown();
The above is safe because all conversions are done concurrently but the main thread blocks until all futures have completed. Future::get
blocks until its conversion has completed but returns immediately if a conversion already is complete. This way you make sure you do not reach shutDown
before all conversions are complete.
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.