Last active
November 28, 2019 08:55
-
-
Save dmi3coder/928de8bac6a477060ef9a6ed36d93278 to your computer and use it in GitHub Desktop.
Cached annotation example in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Main { | |
@Retention(RetentionPolicy.RUNTIME) | |
@interface Cached { } // Nothing inside our annotation | |
static class SomeObject { | |
@Cached | |
public String intensiveTask() throws InterruptedException { | |
Thread.sleep(1000); | |
return "expensive task result"; | |
} | |
} | |
static class SomeObjectExecutor { | |
Map<String, String> cache = new HashMap<>(); | |
public String execute(SomeObject task) throws Exception { | |
final Method intensiveTaskMethod = task.getClass().getDeclaredMethod("intensiveTask"); | |
if (intensiveTaskMethod.isAnnotationPresent(Cached.class)) { | |
String className = task.getClass().getName(); | |
if (!cache.containsKey(className)) { | |
cache.put(className, task.intensiveTask()); | |
} | |
return cache.get(className); | |
} | |
return task.intensiveTask(); | |
} | |
} | |
public static void main(String[] args) throws Exception { | |
final SomeObjectExecutor someObjectExecutor = new SomeObjectExecutor(); | |
long time = System.currentTimeMillis(); | |
final SomeObject expensiveTaskObject = new SomeObject(); | |
someObjectExecutor.execute(expensiveTaskObject); | |
System.out.println("First execution:" + (System.currentTimeMillis() - time)); | |
time = System.currentTimeMillis(); | |
someObjectExecutor.execute(expensiveTaskObject); | |
System.out.println("Second execution:" + (System.currentTimeMillis() - time)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment