Search code examples
maven-3maven-pluginparallel-builds

how to make sure that a maven plugin is thread safe


I have few maven plugins that were developed in my team, and those plugins are not marked @threadSafe. I have run around 50 jobs and I do not see in inconsistency, but I would like to know if there is way to verify this programmatically.

And what would be the things to look for which will make the plugin unsafe for multithreading


Solution

  • Based on https://cwiki.apache.org/confluence/display/MAVEN/Parallel+builds+in+Maven+3, a mojo is considered threadSafe as long as there's no mutable state that is shared across different instances of the mojo -- e.g. a static reference to an object with mutable contents.

    When a single module is being built, an instance of the mojo is created, and its execute() method is called once, on a single thread.

    OTOH if two modules are being built, and neither depends on the other, separate instances of the mojo are created (one for each module), and their execute() methods may get called simultaneously on different threads -- if the -T cli flag is used and relevant mojos are threadSafe.

    The link above lists some specific things to check for:

    • Check all static fields/variables in plugin/plugin code are not subject to threading problems.
    • You might want to pay special attention to static member variables of the subclasses of java.text.Format (NumberFormat, DateFormat, etc.), most of which are not thread-safe and cannot be shared as static variables.
    • Check any plexus components.xml; if the components defined are singletons they need to be thread-safe.
    • Check for presence of known tainted libraries.
    • Check thread safety of any other third party libraries. This last item can be a bit hard, but inquiries on mailing lists can get you a long way.

    In theory, two different module builds could still get into a race by e.g. writing to the same file. That doesn't seem to be what the threadSafe annotation tag is concerned with ... maybe because in practice the vast majority of module builds write files only inside their own module directories.