Report abuse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package net.peierls.util;

import java.util.concurrent.TimeUnit;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Provider;

/**
 * An artificial example of using ConcurrentSingletonScope.
 */
public class ConcurrentSingletonExample {

    public static void main(String... args) throws InterruptedException {
        long start = System.nanoTime();

        Injector injector = Guice.createInjector(
            new AbstractModule() {
                public void configure() {
                    bind(A.class);
                    bind(B.class);
                    bind(C.class);
                    ConcurrentSingletonScope.install(binder());
                }
            }
        );

        A a = injector.getInstance(A.class);

        long elapsed = System.nanoTime() - start;

        System.out.printf("Completed in %d seconds%n", TimeUnit.NANOSECONDS.toSeconds(elapsed));
    }

    // Concurrently provided "services" A, B, and C. A depends on B and C.

    @ConcurrentSingleton
    static class A {
        @Inject public A(Provider<B> b, Provider<C> c) {
            try {
                System.out.printf("Starting A on thread %s%n", Thread.currentThread().getName());
                TimeUnit.SECONDS.sleep(1);
                System.out.printf("A getting B and C instances on thread %s%n", Thread.currentThread().getName());
                b.get();
                c.get();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                System.out.println("Started A");
            }
        }
    }

    @ConcurrentSingleton
    static class B {
        @Inject public B() {
            try {
                System.out.printf("Starting B on thread %s%n", Thread.currentThread().getName());
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                System.out.println("Started B");
            }
        }
    }

    @ConcurrentSingleton
    static class C {
        @Inject public C() {
            try {
                System.out.printf("Starting C on thread %s%n", Thread.currentThread().getName());
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                System.out.println("Started C");
            }
        }
    }
}