How do you create a custom Guice UI area?

It seems that all Guice implementation implementations out of the box are essentially streaming (or ignoring streams entirely):

Scopes.SINGLETON and Scopes.NO_SCOPE ignore streams and are edge cases: global scope and scope.

ServletScopes.REQUEST and ServletScopes.SESSION ultimately depend on retrieving objects with a scope from ThreadLocal<Context> . The restored Context contains a link to the HttpServletRequest , which contains a link to objects with a storage area stored as named attributes (where the name is obtained from com.google.inject.Key ).

The SimpleScope class from the user area. The Guice wiki also provides a stream implementation using the member variable ThreadLocal<Map<Key<?>, Object>> .

With this preamble, my question is this: how do I create a non-Thread-scope Scope? It seems that something I can use to search for Map<Key<?>, Object> is missing, since the only thing passed to Scope.scope() is Key<T> and a Provider<T> .

Thanks in advance for your time.

+4
source share
1 answer

Itโ€™s a little unclear what you want โ€” you donโ€™t want areas based on threads to not have areas that ignore threads.

But yes, scopes are designed to control the life cycle of an object and say when an instance should be reused. So you really ask: "What are the other options for reusing an instance outside of" always use the same instance "," never use the same instance ", and" use the instance depending on the runtime of the current thread ",? "

Here's what comes to mind:

  • Use the same instance for a fixed time. An example here is a configuration file that reloads and is reviewed every ten minutes.
  • Make some kind of network call to ask if the given object should be reused (perhaps this is a quick call to determine whether to restore the object, but the call to restore the object is slow)
  • Reuse the same object until there is some external call in which we are told to reload
  • Repeat the use of the same object in the stream, but not with the area explicitly entered and left as the servlet area. (So, one instance for the thread)
  • The scope of this thread and child threads is based on InheritableThreadLocal , not a simple ThreadLocal .
  • In this regard, Scope and the thread-based ExecutorService thread that run the togehter so that instances are split between the thread and the jobs it sends to run the background.
  • Pull instances from the pool; this is tricky since we will need a good way to return objects to the pool when done. (Perhaps you could combine this idea with something like a request scope so that objects can be returned to the pool when the request completes)
  • An area that consists of two or more other areas, so we could get a configuration object that is re-read every 10 minutes, except that the same instance is used over the lifetime of this request.
+7
source

Source: https://habr.com/ru/post/1304919/


All Articles