title: Are AspectJ aspects Singletons?
body: <p>When creating aspects using the <a href="https://github.com/eclipse/org.aspectj/blob/master/runtime/src/main/java/org/aspectj/lang/annotation/Aspect.java" rel="nofollow noreferrer">Aspect annotation</a> as described <a href="https://www.eclipse.org/aspectj/doc/released/adk15notebook/ataspectj-aspects.html" rel="nofollow noreferrer">here</a>, is it possible to use this annotation with a class that contains a state (e.g. member variables that change as soon as a pointcut is hit)? Or in other words: is an aspect class a singleton? The source code of the annotation suggests something like this, but I cannot find more details in the documentation.</p>
  
  <p>An example: here is an aspect that counts how often a method has been called. The aspect stores the number of invocations in a map and prints out the map:</p>
  
  <pre class="lang-java prettyprint-override"><code>@Aspect
  public class CountAspect {
  
      private Map&lt;String, Integer&gt; counter = new HashMap&lt;&gt;(); 
  
      @Before("execution(* *.*(..))")
      public void countMethodCalls(JoinPoint jp) {
          String methodName = jp.getSignature().getName();
          counter.merge(methodName, 1, Integer::sum);
          System.out.println(counter);
      }
  }
  </code></pre>
  
  <p>When testing this aspect everthing works as expected. When calling methods <code>a</code>, <code>b</code> and <code>c</code> several times, the output is</p>
  
  <pre class="lang-none prettyprint-override"><code>{main=1}
  {a=1, main=1}
  {a=1, b=1, main=1}
  {a=1, b=1, c=1, main=1}
  {a=2, b=1, c=1, main=1}
  {a=3, b=1, c=1, main=1}
  </code></pre>
  
  <p>Is this result reliable? Or does my example only work because I have a rather simple example here? </p>
  
  <p>Could it happen that in a more complex scenario, a second instance of <code>CountAspect</code> would be created by the AspectJ runtime and thus I would lose data collected in the <code>counter</code> map until then?</p>
  
  <p>I am using Load-Time Weaving if that matters.</p>