简体   繁体   中英

Uses of custom annotations, how to

Suppose you set up a custom annotation

public @interface ThreadSafe {
}

To indicate to the reader of your code that classes or methods are in fact Thread Safe

Other then a variant of a comment, how else can these types of custom annotations be used?

If you're just asking about potential applications of such an annotation, here's a few off the top of my head...

  • Reflective code might take advantage of the thread-safety of annotated methods. For example, Guava's EventBus uses an @AllowConcurrentEvents annotation as a hint for its EventBus framework.
  • Static analysis tools can use annotations as hints -- either that a method should have a certain property, or that users of this method can assume a certain property. For example, a static analysis tool might perform extra checks on methods annotated @ThreadSafe to make sure they are, in fact, thread safe.
  • You could design preprocessors that might identify optimization opportunities that are only available because a specific method is thread-safe.

Such annotations can bring information that could be used to improve the efficiency of algorithms. The RandomAccess interface is used for this purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM