fork(4) download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. import java.util.function.Supplier;
  6.  
  7. class Ideone
  8. {
  9.  
  10.  
  11. @FunctionalInterface
  12. public interface Lazy<T> extends Supplier<T> {
  13. abstract class Cache {
  14. private volatile static Map<Integer, Object> instances = new HashMap<>();
  15.  
  16. private static synchronized Object getInstance(int instanceId, Supplier<Object> create) {
  17.  
  18. Object instance = instances.get(instanceId);
  19. if (instance == null) {
  20. synchronized (Cache.class) {
  21. instance = instances.get(instanceId);
  22. if (instance == null) {
  23. instance = create.get();
  24. instances.put(instanceId, instance);
  25. }
  26. }
  27. }
  28. return instance;
  29. }
  30. }
  31.  
  32. @Override
  33. default T get() {
  34. return (T) Cache.getInstance(this.hashCode(), () -> init());
  35. }
  36.  
  37. T init();
  38. }
  39.  
  40.  
  41. static Lazy<String> name1 = () -> {
  42. System.out.println("lazy init 1");
  43. return "name 1";
  44. };
  45.  
  46. static Lazy<String> name2 = () -> {
  47. System.out.println("lazy init 2");
  48. return "name 2";
  49. };
  50.  
  51.  
  52. public static void main (String[] args) throws java.lang.Exception
  53. {
  54. System.out.println("start");
  55. System.out.println(name1.get());
  56. System.out.println(name1.get());
  57. System.out.println(name2.get());
  58. System.out.println(name2.get());
  59. System.out.println("end");
  60. }
  61.  
  62. }
Success #stdin #stdout 0.22s 320704KB
stdin
Standard input is empty
stdout
start
lazy init 1
name 1
name 1
lazy init 2
name 2
name 2
end