Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

java - custom Guice binding annotations with parameters

I have successfully created a Guice binding annotation to inject single threaded java.util.concurrent.ExecutorService instances into a constructor.

here is an example usage:

public class ContainsSingleThreadedExecutorService {


    private final ExecutorService executorService;

    @Inject
    public ContainsSingleThreadedExecutorService(@SingleThreaded ExecutorService executorService) {

        this.executorService = executorService;
    }

}

I now want to create a similar annotation for multi-threaded executors, specifying the ThreadPool size in the annotation. For example:

public class ContainsMultiThreadedExecutorService {


    private final ExecutorService executorService;

    @Inject
    public ContainsMultiThreadedExecutorService(@MultiThreaded(poolSize = 5) ExecutorService executorService) {

        this.executorService = executorService;
    }

}

Does anyone out there know how I can access the value of the "poolSize" parameter from a Guice Provider?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can't. That's not how binding annotations are intended to be used... the parameter would only serve to differentiate an ExecutorService bound with @MultiThreaded(poolSize = 5) from one bound with @MultiThreaded(poolSize = 2). It's not metadata to help configure a Provider.

If you inject something annotated with @MultiThreaded(poolSize = 5), you need to have bound something with the annotation @MultiThreaded(poolSize = 5). If you then want to change the pool size you're using in all those places, you need to change poolSize = 5 to poolSize = 4 in both the place(s) where you bind it and in all the places you inject it. This doesn't make much sense to me.

Instead of binding ExecutorServices by how many threads they have in their thread pool, you should bind them according to what you want to use them for. Then you can adjust the numbers of threads each one uses in one place.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...