Mikesname
Mikesname

Reputation: 8901

Play Framework 2 - thread safety for view helper functions

I'm interested to know to what extent thread safely needs to be a concern in Play 2's view functions. For example, I'm using the PegDown markdown renderer in my Play 2.2 project for rendering lots of small snippets of markdown via a view helper function.

Since there's apparently overhead to creating an instance of the PegDownProcessor it seems sensible to re-use the instance for each individual snippet. However, since PegDownProcessor instances are apparently not thread safe I'm wondering if I need to explicitly use a ThreadLocal for this, i.e, instead of:

object ViewHelpers {
  import org.pegdown.PegDownProcessor
  private val markdownProcessor = new PegDownProcessor

  def renderMarkdown(text: String) = markdownProcessor.markdownToHtml(text)
}

something like:

object ViewHelpers {
  import org.pegdown.PegDownProcessor
  private val markdownProcessor = new ThreadLocal[PegDownProcessor]

  private def getMarkdownProcessor = {
    Option(markdownProcessor.get) getOrElse {
      val processor = new PegDownProcessor
      markdownProcessor.set(processor)
      processor
    }
  }

  def renderMarkdown(text: String) = getMarkdownProcessor.markdownToHtml(text)
}

While this could be seen as premature optimisation, I'd be interested in finding out whether the threadlocal approach is necessary or if there's some protection in the Play framework itself (or Scala, for that matter) that would make it superfluous.

Or, for that matter, if there's a better alternative approach.

Upvotes: 1

Views: 230

Answers (1)

Fletcher T. Penney
Fletcher T. Penney

Reputation: 350

I am not familiar with PegDown or the Play framework, so I can't address that part of your question.

But if you can use C libraries in your project, MultiMarkdown 4 is thread safe and high performance and may be a useful alternative approach. I use it in MultiMarkdown Composer, which can have multiple instances of the parser running simultaneously for different purposes without collisions.

https://github.com/fletcher/MultiMarkdown-4/

http://fletcherpenney.net/multimarkdown/

Upvotes: 1

Related Questions