-1

Guice has the concept of a Scope, commonly used for a web server request.

Are Scopes viable for use in a long-lived object, whose lifecycle may be asynchronous compared to the running code?

E.g. Sponge & Bukkit both provide events that fire when a world is loaded / unloaded.

These worlds are then ticked, and various events thrown.

Is it worthwhile using Scopes and Scoping annotations in order to have an annotation that takes a parameter, in order to inject / initialize services / world specific listeners whenever a world is loaded and unloaded?

public abstract class WorldService {
    World world;

    public WorldService(World world) {
        this.world = world;
    }

    abstract void tick();
    abstract void start();
    abstract void stop();

    public static class TimeTracker extends WorldService {
        private final Logger logger;
        private int count;

        @Inject
        public TimeTracker(World world, Logger logger) {
            super(world);
            this.logger = logger;
        }

        @Override
        void tick() {
            count++;
        }

        @Override
        void start() {
            count = 0;
        }

        @Override
        void stop() {
            logger.debug("World loaded for "+count+" ticks");
        }
    }
}
Ryan Leach
  • 4,262
  • 5
  • 34
  • 71
  • To the downvoters and close voter, I would appreciate a comment saying what I was failing to communicate. – Ryan Leach Jun 13 '18 at 05:21
  • *`Is it worthwhile using Scopes?`* Is a hugely "primarily opinion based" sort of question. As for not communicating well ("unclear what you are asking"), it probably has to do with people not understanding Scopes and why its relevant here. – Draco18s no longer trusts SE Jun 13 '18 at 05:58
  • Often questions like this can be answered with "no, you are crazy to even think that they are possibly applicable in this area" and 'too broad' means, "yes, but there are many ways to do it" yet people still close the question. – Ryan Leach Jun 13 '18 at 06:26

1 Answers1

0

https://github.com/timboudreau/scopes Provides a library that allows defining your own Scopes.

If you are inside a ReentrantScope, and dispatch a Runnable to an ExecutorService wrappered via this method, the current scope contents will be frozen and reconstituted before the Runnable runs - so you get identical scope contents to what you had when you submitted teh Runnable.

This way it is possible to have all of the benefits of scoping, and have a complex threading model.

So not only can you have custom scopes with this library, but you can successfully pass the objects through scheduled tasks, potentially in combination with Aikar's Task Chains!

This allows for some very neat and tidy code.

Ryan Leach
  • 4,262
  • 5
  • 34
  • 71