Skip to content

Commit

Permalink
Make caching for getHandlerList MethodHandles
Browse files Browse the repository at this point in the history
  • Loading branch information
Brikster committed Nov 18, 2023
1 parent f392125 commit 82bff91
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions spigot/src/main/java/ru/brikster/chatty/util/ListenerUtil.java
Original file line number Diff line number Diff line change
@@ -1,20 +1,30 @@
package ru.brikster.chatty.util;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import lombok.experimental.UtilityClass;
import org.bukkit.event.HandlerList;
import org.bukkit.plugin.Plugin;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.time.Duration;

@UtilityClass
public class ListenerUtil {

private final static Cache<Class<?>, MethodHandle> EVENT_CLASS_METHOD_HANDLE_CACHE = CacheBuilder
.newBuilder()
.expireAfterAccess(Duration.ofMinutes(30))
.build();

public void unregister(Class<?> eventClazz, Plugin plugin) {
try {
HandlerList handlerList = (HandlerList) MethodHandles.publicLookup()
.findStatic(eventClazz, "getHandlerList", MethodType.methodType(HandlerList.class))
.invoke();
MethodHandle methodHandle = EVENT_CLASS_METHOD_HANDLE_CACHE.get(eventClazz, () -> MethodHandles.publicLookup()
.findStatic(eventClazz, "getHandlerList", MethodType.methodType(HandlerList.class)));

HandlerList handlerList = (HandlerList) methodHandle.invoke();
handlerList.unregister(plugin);
} catch (Throwable e) {
throw new RuntimeException(e);
Expand Down

0 comments on commit 82bff91

Please sign in to comment.