Menu

#7 RTFTemplate not thread safe

v1.0 (example)
open
5
2013-05-24
2013-05-24
No

Hallo,
I use RTF template library in our project, thanks for your open source contribution. I was confronted with following behaviour:

If two threads run java code like the one shown on the top of page http://rtftemplate.sourceforge.net/userguide/integration-rtftemplate-java/integration-rtftemplate-java.html , race condition can happen. According to your internal spring configuration, bean vmRTFTemplate has prototype scope but defaultRTFParser has singleton scope. Hence, every new call of builder.newRTFTemplate() creates new instance with the same autowired field parser. Since RTFDocumentHandler stores state of automaton into currentRTFElement field, field can be overwritten by different thread.

My workaround is to ignore spring singleton and explicitly setParser(new RTFDocumentHandler()); after template creation. However I think the parser should also be of prototype scope in spring context.

I reproduced this bug in a test with 40 concurrent threads which repeatedly generated RTF (model template was the same every time but parameters differed). Strange behaviour comprised ArraysIndexOutOfBoundsExceptions, StringIndexOutOfBoundsExceptions, IOException("Current RTF element is null. RTF stream is not valid.") or inappropriately long and corrupted RTF files (4MB where 50k was expected, probably due to returning state of automaton to former position). After applying workaround race conditions dismissed.

Thanks for response
Tomáš Záluský

Discussion

  • Angelo Zerr

    Angelo Zerr - 2013-05-24

    Hi Tomáš,

    I'm sorry but I have gaven RTFTemplate for XDocReport https://code.google.com/p/xdocreport/

    If you can use docx or odt as template source (instead of using RTF), I suggest really to switch to XDocReport. It is more performant, can convert to PDF or XHTML, manage text styling (set html in your context to style text (bold, italic, etc) instead simple text).

    Regards Angelo

     

    Last edit: Angelo Zerr 2013-05-24
  • Tomáš Záluský

    Hi Angelo, thanks for quick response.
    It is no problem for us to try XDocReport, sometimes we will explore it and according to amount of migration work we perhaps migrate. I hope this issue doesn't reproduce in XDocReport.
    Maybe could the existence of new library be better communicated on main pages of RTFTemplate - http://rtftemplate.sourceforge.net/ and https://sourceforge.net/projects/rtftemplate/ ? Or did I miss something?
    Thanks
    Tomáš

     

Log in to post a comment.

MongoDB Logo MongoDB