Solved Just a question...

Discussion in 'Spigot Plugin Development' started by Wilsoon, Jan 16, 2020.

Thread Status:
Not open for further replies.
  1. So my Listener class is called EventHandling, and I only have one listener, I want to disable and enable that listener at times, how would I do it?
     
  2. Multiple options available e.g.:
    • Unregister the Listener
    • inject a flag that you can toggle
     
  3. I think injecting a flag would be better for me, may I know how would I do it? (Please note that I would require that flag to be able to be checked for it's value as I need the flag for toggle Listener On and Listener Off)
     
  4. Create a class with a private boolean attribute, a Getter and Setter.
    Instantiate the Object once in your class where you instantiate the Listener.
    Pass it to the constructor of you listener and pass the same instance into your constructor of your class where you want to set the state e.g. a class implementing CommandExecuter.
     
    #4 ysl3000, Jan 16, 2020
    Last edited: Jan 16, 2020
  5. I've learnt a little bit of Java, but not enough to understand this fully.

    My code (Main):

    Code (Java):
    package com.gmail.calorious.wergteleport;

    import org.bukkit.plugin.java.JavaPlugin;

    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.plugin.PluginDescriptionFile;


    @SuppressWarnings("unused")

    public class Main extends JavaPlugin {
    private boolean Flag;
        @Override
       public void onEnable() {
       getServer().getPluginManager().registerEvents(new EventHandling(), this); // Register Events (EventHandling.class)
       getLogger().info(ChatColor.GOLD + "Hooking to WorldEdit...");
       if(getServer().getPluginManager().getPlugin("WorldEdit") == null) {
            getLogger().info(ChatColor.RED + "Failed to hook to WorldEdit!");
            getLogger().info(ChatColor.RED + "This plugin requires WorldEdit to function.");
            getLogger().severe(ChatColor.DARK_RED + "STOPPING PLUGIN: " + getDescription().getName()); //Throws an ERROR message
            getLogger().severe(ChatColor.DARK_RED + "Reason: Dependent Plugin not found.");  //Throws an ERROR message
            getLogger().severe(ChatColor.DARK_RED + "Required Plugins: " + getDescription().getSoftDepend()); //Throws an ERROR message
            getPluginLoader().disablePlugin(this);
       }
       else {
             getLogger().info(ChatColor.GREEN + "Successfully hooked to WorldEdit!");
           }
        }
        @Override
        public void onDisable() {
            getLogger().info(ChatColor.DARK_RED + "[WERegionTeleport Disabled]");
            getLogger().info(ChatColor.RED + " Plugin has disabled successfully!");
        }
        public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
            if(cmd.getName().equalsIgnoreCase("wergtp")) {
                if(args.length == 0) {
                    sender.sendMessage(ChatColor.GREEN + "WorldEdit Region Teleport");
                    sender.sendMessage(ChatColor.GREEN + "----------------------------");
                    sender.sendMessage(ChatColor.GOLD + "  /wergtp on - Enable the plugin");
                    sender.sendMessage(ChatColor.GOLD + "  /wergtp off - Disable the plugin");
                    sender.sendMessage(ChatColor.GREEN + "----------------------------");
                    return true;
                }
                if(args.length == 1) {
                    if(args.toString() == "on") {
                       
                    }
                }
            }
            return false;
        }
    }
     


    Listener:

    Code (Java):
    package com.gmail.calorious.wergteleport;

    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.player.*;

    public class EventHandling implements Listener {
        @EventHandler
        public void onPlayerMove(PlayerMoveEvent e) {
           
        }
    }
     
  6. Basically what you want to do is the following:

    Code (Java):
    package com.gmail.calorious.wergteleport;

    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.player.*;

    public class EventHandling implements Listener {

        private boolean enabled = true;

        @EventHandler
        public void onPlayerMove(PlayerMoveEvent e) {
            if (enabled) {
                // do your event handling here
            }
        }

        public void setEnabled(boolean enabled) {
            this.enabled = enabled;
        }
    }
    Now in your main class:

    Code (Java):
    public class Main extends JavaPlugin {

        private EventHandling eventHandler;

        // ...
       
        getServer().getPluginManager().registerEvents(this.eventHandler = new EventHandling(), this);

       // ...

    }
    Now you can enable or disable the EventHandler in your main class in whatever way you so desire to do.
    If you want to enable/disable this from any other class, simply pass the reference to the event handler, or (this is better because there is no reason to make it visible to other classes) create a method enableListener(boolean enable) in your main class
     
  7. this makes more sense, thanks!
     
  8. The more efficient (and cleaner) way is to unregister the listener for most cases
    HandlerList#unregisterAll(<your listener>)
     
  9. I doubt that that would be more efficient. Maybe cleaner, but that's disputable imo.
    The process of unregistering a Listener has a complexity O(N), where N is the count of registered Listeners (and I believe all Listeners from every plugin are handled in a single HandlerList).
    Simply having a boolean check has practically no overhead at all, and the unregistered event is fired anyway, no matter if you are unregistering the listener or not.

    I would only agree with you when you are talking about unregistering the listener and never subscribing to it again, resp. only subscribing after a long time.

    Edit: also what @Blutkrone said
     
  10. This is arguable, unless I remember wrong unloading a listener will cause you to rebake the internal handler mappings which can become hella expensive. Someone needs to measure the performance expenditure generated between the reflection invocation of the listener and the performance expenditure generated from registration.
     
    • Agree Agree x 1
  11. As i said, more efficient in most cases, whenever i've seen this asked it was because they wnated a part of their plugin disabled, if you have a listener on player move event, with 20 players, that's 400 checks of that Boolean and event calling per second on a useless listener per second

    If you are enabling and disabling it every so and so, then yes, a boolean is for you.

    Edit: I know events are always fired, But you have to understand it is calling each registered listener with the annotated method 400 times per second in this example, that adds up quickly, chances are there is a plugin doing something useful on that event anyway.
     
  12. I mean... 400 boolean checks per second... if we assume one check can be done in one CPU clock cycle (not unusual), we have (simplified calculation on an Intel i7) ~ 300 MIPS - 400 operations per second = 299.9996 MIPS;
    so in this case by the waste of 400 checks, you would be at a devastating loss of efficiency of about 0.0001%
    And most CPU's that people own here are even faster.
     
  13. Also, that efficiency loss is not one time, it is continuous, calling unregister is a one time deal.
    There is also the fact of event calling as i pointed out, anyway i think this thread is answered.
     
    #13 Enfield, Jan 17, 2020
    Last edited: Jan 17, 2020
  14. Choco

    Moderator

    Events get created and processed regardless of whether or not something is listening to it. It's just a matter of passing the event instance to the listeners in the handler list. A boolean is the correct solution here. Please don't continue arguing a point that's already been shown to be ineffective.
     
    • Optimistic Optimistic x 1
  15. I'ma just close this
     
    • Winner Winner x 2
Thread Status:
Not open for further replies.