Annotation Type WithCaching


  • @Target({PARAMETER,FIELD})
    @Retention(RUNTIME)
    public @interface WithCaching
    An injected Instance annotated with this annotation will cache the result of the Provider.get() operation.

    The result is "computed" on the first call to Provider.get() and the same value is returned for all subsequent calls, even for Dependent beans.

    Example

     
      class Producer {
         
         long nextLong = 0;
         int nextInt = 0;
      
         @Dependent
         @Produces 
         Integer produceInt() {
           return nextInt++;
         }
         
         @Dependent
         @Produces 
         Long produceLong() {
           return nextLong++;
         }
      }
      
      class Consumer {
      
         @Inject
         Instance<Long> longInstance;
      
         @WithCaching
         @Inject
         Instance<Integer> intInstance;
         
         // this method should always return true and Producer#produceInt() is only called once 
         boolean pingInt() {
            return intInstance.get().equals(intInstance.get());
         }
         
         // this method should always return false and Producer#produceLong() is always called twice 
         boolean pingLong() {
            return longInstance.get().equals(longInstance.get());
         }
      }
      
     

    Cache Invalidation

    It is possible to invalidate the cache via the InjectableInstance.clearCache() method.

     
      class Consumer {
      
         @WithCaching
         @Inject
         InjectableInstance<Integer> instance;
         
         int ping(boolean clearCache) {
            if (clearCache) {
              instance.clearCache();
            }
            return instance.get();
         }
      }
      
     
    See Also:
    Instance, InjectableInstance.clearCache()