groovy/groovy-core — pull request #256 by jacopoc (2013-09-26 14:17:03+00:00)
Title: More efficient implementation of thread safety in class ClassLoaderForClassArtifacts

Pull request for: http://jira.codehaus.org/browse/GROOVY-6364

Refactored thread safety implementation of method createClassName in order to improve its performance

*Current Status*

In the class ClassLoaderForClassArtifacts, the method createClassName is synchronized in order to implement thread safety for the operations in the class' private field allocatedNames (that is a set). The method generates, in a thread safe way, a unique name for the class by appending an index suffix to the class name.

*The Problem*
Under heavy server load (a lot of garbage collections etc) we have noticed that several threads were blocked waiting to acquire a lock on objects of class ClassLoaderForClassArtifacts; the objects were locked by another thread executing the (synchronized) method createClassName and possibly slow running because of gc or other factors.
By reviewing the content of the createClassName method we have realized that most of the operations performed there do not actually require a lock and that was actually possible to reimplement the method to make it more efficient and of course also preserve its thread safety.

*The Proposed Solution*
The modification proposed in this Jira ticket, while maintaining the same behavior of the method and its class, reimplements the thread safety to make it more efficient.
Here are the main changes introduced:
* the Set named allocatedNames is replaced by an AtomicInteger field, that is used as a thread safe counter that maintains the next suffix to be used for class names
* the code in createClassName has been reimplemented to make use of the new (more efficient and still thread safe) mechanism to generate class names sequences like className, className$0, className$1, etc
* the synchronized keyword has been removed from the method because no longer needed because thread safety is already guaranteed

This modification has been tested in the trunk but the same issue is present in the version 1.8.* and can be applied there as well.