make it async
- User
make it async
Assistant
Okay, let's refactor the
SellAxeplugin to perform the potentially slow ShopGUI+ price lookups asynchronously. This prevents the main server thread from freezing if a player sells a large chest full of items.Key Changes:
- Copy Inventory: We'll copy the chest's contents before going async, as accessing the live inventory from another thread is unsafe.
- Async Price Calculation: A separate thread will iterate through the copied items and calculate the total sell price using the ShopGUI+ API.
- Sync Callback: Once the async task finishes, it schedules another task back on the main thread to:
- Check if the player is still online and the chest is still valid.
- Remove the original items from the chest.
- Deposit the money via Vault.
- Send the message.
- Damage the axe.
1.
pom.xmlandplugin.yml(No changes needed)
2. Main Class (
SellAxe.java) - Updatedpackage com.yourname.sellaxe; import me.brcdev.shopgui.ShopGuiPlusApi; import net.milkbowl.vault.economy.Economy; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.NamespacedKey; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.Container; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.meta.Damageable; import org.bukkit.persistence.PersistentDataType; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.event.Listener; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.block.Action; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class SellAxe extends JavaPlugin implements Listener { private Economy econ; private NamespacedKey key; // PDC key to tag the axe @Override public void onEnable() { // Vault if (!setupEconomy()) { getLogger().severe("Vault not found! Disabling."); getServer().getPluginManager().disablePlugin(this); return; } // ShopGUI+ soft check if (!getServer().getPluginManager().isPluginEnabled("ShopGUIPlus")) { getLogger().severe("ShopGUIPlus not found! Disabling."); getServer().getPluginManager().disablePlugin(this); return; } key = new NamespacedKey(this, "sellaxe"); getServer().getPluginManager().registerEvents(this, this); saveDefaultConfig(); // creates config.yml w/ default messages getLogger().info("SellAxe enabled!"); } /* ====================================================== == EVENT LISTENER == ====================================================== */ @EventHandler public void onInteract(PlayerInteractEvent e) { // --- Initial Checks (Main Thread) --- if (!(e.getAction() == Action.RIGHT_CLICK_BLOCK)) return; Block clickedBlock = e.getClickedBlock(); if (clickedBlock == null) return; Material type = clickedBlock.getType(); if (type != Material.CHEST && type != Material.TRAPPED_CHEST && type != Material.BARREL) return; ItemStack hand = e.getItem(); if (!isSellAxe(hand)) return; e.setCancelled(true); // Prevent chest opening immediately Player p = e.getPlayer(); UUID playerUUID = p.getUniqueId(); // Store UUID for async task Location blockLocation = clickedBlock.getLocation(); // Store location // --- Prepare Data for Async Task (Main Thread) --- Inventory chestInv = ((Container) clickedBlock.getState()).getInventory(); List<ItemStack> itemsToSell = new ArrayList<>(); // IMPORTANT: Create copies of the ItemStacks for the async task for (ItemStack stack : chestInv.getContents()) { if (stack != null && stack.getType() != Material.AIR) { itemsToSell.add(stack.clone()); // Clone the stack! } } if (itemsToSell.isEmpty()) { p.sendMessage(color(getConfig().getString("messages.nothing"))); return; // No need to go async if empty } // --- Schedule Asynchronous Calculation --- Bukkit.getScheduler().runTaskAsynchronously(this, () -> { double totalValue = 0; List<ItemStack> soldItemsOriginalReference = new ArrayList<>(); // To track which *original type/amount* got sold // --- Price Calculation (Async Thread) --- // Note: Accessing player object here for permissions *might* be okay with SGP API, // but if issues arise, might need to check permissions beforehand or use UUID-based checks if API supports. // For now, we pass the Player object directly. Test this under load. Player asyncPlayer = Bukkit.getPlayer(playerUUID); // Get player reference (might be null if logged off) if (asyncPlayer == null || !asyncPlayer.isOnline()) { // Optionally log this or handle differently return; // Player logged off before calculation finished } for (ItemStack itemCopy : itemsToSell) { double price = ShopGuiPlusApi.getItemStackPriceSell(asyncPlayer, itemCopy); if (price > 0) { totalValue += price; soldItemsOriginalReference.add(itemCopy); // Add the copy, we'll match it later } } // --- Schedule Final Actions Back on Main Thread --- final double finalTotalValue = totalValue; // Effectively final for lambda Bukkit.getScheduler().runTask(this, () -> { // --- Final Checks & Actions (Main Thread) --- Player mainThreadPlayer = Bukkit.getPlayer(playerUUID); if (mainThreadPlayer == null || !mainThreadPlayer.isOnline()) { return; // Player logged off } Block currentBlock = blockLocation.getBlock(); if (currentBlock.getType() != type || !(currentBlock.getState() instanceof Container)) { mainThreadPlayer.sendMessage(color(getConfig().getString("messages.chest_gone"))); // Or some other error return; // Chest was broken or changed } Inventory currentChestInv = ((Container) currentBlock.getState()).getInventory(); // --- Remove Items and Pay --- if (finalTotalValue > 0) { // Remove the items that were successfully priced from the *actual* chest // We iterate through the copies we priced and remove matching stacks from the real inventory // This is slightly less efficient but safer than passing mutable itemstack lists between threads for (ItemStack soldItemCopy : soldItemsOriginalReference) { // Find and remove a matching stack in the current inventory // Note: This removes *one* stack matching the sold item copy per iteration. // If multiple identical stacks existed, ShopGUI+ price check should have handled the total quantity. // We remove based on the total price calculated for the stack copy. currentChestInv.removeItem(soldItemCopy); // Use the copy to find a match } econ.depositPlayer(mainThreadPlayer, finalTotalValue); mainThreadPlayer.sendMessage(color(getConfig().getString("messages.sold") .replace("{money}", String.format("%.2f", finalTotalValue)))); // Optional: Damage the axe slightly (back on main thread) ItemStack currentHand = mainThreadPlayer.getInventory().getItemInMainHand(); // Re-get item in hand if (isSellAxe(currentHand) && currentHand.getItemMeta() instanceof Damageable dmg) { // Check again in case they swapped item dmg.setDamage(dmg.getDamage() + 1); // Configurable amount later? if(dmg.getDamage() >= currentHand.getType().getMaxDurability()) { mainThreadPlayer.getInventory().setItemInMainHand(null); // Break axe mainThreadPlayer.playSound(mainThreadPlayer.getLocation(), org.bukkit.Sound.ENTITY_ITEM_BREAK, 1.0f, 1.0f); } else { currentHand.setItemMeta((ItemMeta) dmg); } } } else { // This case should ideally be caught before going async, but as a fallback: mainThreadPlayer.sendMessage(color(getConfig().getString("messages.nothing"))); } }); }); } /* ====================================================== == COMMAND == (No changes needed) ====================================================== */ @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (!(sender instanceof Player p)) { sender.sendMessage("Player only."); return true; } if (args.length == 1 && args[0].equalsIgnoreCase("give")) { if (!p.hasPermission("sellaxe.give")) { p.sendMessage(ChatColor.RED + "No permission."); return true; } ItemStack axe = createSellAxe(); p.getInventory().addItem(axe); p.sendMessage(ChatColor.GREEN + "Enjoy your Sell Axe!"); return true; } p.sendMessage(ChatColor.RED + "/sellaxe give"); return true; } /* ====================================================== == UTILITY == (Minor changes below) ====================================================== */ private boolean setupEconomy() { if (getServer().getPluginManager().getPlugin("Vault") == null) return false; RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class); if (rsp == null) return false; econ = rsp.getProvider(); return econ != null; } private ItemStack createSellAxe() { ItemStack axe = new ItemStack(Material.DIAMOND_AXE); // Make configurable? ItemMeta meta = axe.getItemMeta(); meta.setDisplayName(color(getConfig().getString("sell-axe.name", "&6Sell Axe"))); // Added config default meta.getPersistentDataContainer().set(key, PersistentDataType.BYTE, (byte) 1); List<String> lore = new ArrayList<>(); for(String line : getConfig().getStringList("sell-axe.lore")) { // Added config default lore.add(color(line)); } if(lore.isEmpty()) { // Default lore if config is missing/empty lore.add(color("&7Right-click chests")); lore.add(color("&7to instantly sell their contents!")); } meta.setLore(lore); axe.setItemMeta(meta); return axe; } private boolean isSellAxe(ItemStack item) { if (item == null || item.getType() == Material.AIR) return false; ItemMeta meta = item.getItemMeta(); if (meta == null) return false; Byte tag = meta.getPersistentDataContainer().get(key, PersistentDataType.BYTE); return tag != null && tag == 1; } private String color(String s) { return ChatColor.translateAlternateColorCodes('&', s); } }
3.
config.yml- Updated with new options# ------------------------- # SellAxe Configuration # ------------------------- # -- Axe Appearance -- sell-axe: material: DIAMOND_AXE # Material of the sell axe item name: '&6Sell Axe' # Display name of the axe lore: # Lore lines below the name - '&7Right-click chests' - '&7to instantly sell their contents!' # damage-per-use: 1 # Future: Add config option for damage # -- Messages -- messages: sold: '&e[SellAxe] &aYou sold the contents for &b${money}&a!' nothing: '&e[SellAxe] &cThere was nothing worth selling in that chest.' chest_gone: '&e[SellAxe] &cThe chest disappeared before selling could complete!' # New message
Explanation of Async Changes:
-
Data Capture (Main Thread):
- Player's UUID and the Block's Location are stored.
- Crucially,
itemsToSell.add(stack.clone());creates copies of theItemStacks. This is vital because the original stacks in thechestInvcannot be safely accessed or modified by the async thread.
-
Async Task (
runTaskAsynchronously):- This code block runs on a separate thread from the main server thread.
- It retrieves the
Playerobject using the stored UUID. It checks if the player is still online. Note: Calling Bukkit API methods likeBukkit.getPlayer()orShopGuiPlusApi.getItemStackPriceSell()from an async thread can sometimes be risky depending on how those APIs are implemented internally. ShopGUI+'s price check likely involves reading data (permissions, prices) which is often safer than writing data, but test this carefully. If you encounter errors related to async access, this part might need further refinement (e.g., checking permissions on the main thread before going async). - It iterates through the copied item list (
itemsToSell) and calculatestotalValue. - It stores which item copies were successfully priced in
soldItemsOriginalReference.
-
Sync Callback (
runTask):- This code block is scheduled to run back on the main server thread after the async task completes.
- It re-checks if the player is online and if the target block is still a valid container at the stored location. This handles cases where the player logs off or the chest is broken while the price calculation was happening.
- It gets the current chest inventory (
currentChestInv). - It iterates through the
soldItemsOriginalReferencelist (the copies that had value) and usescurrentChestInv.removeItem(soldItemCopy)to remove the corresponding original items from the chest.removeItemfinds and removes stacks matching the provided one. - It performs the Vault deposit, sends the message, and applies axe damage – all safe operations on the main thread.
- A check for axe breaking durability was added.
This asynchronous approach makes the server significantly more resilient to lag caused by players using the Sell Axe on large chests. Remember to test thoroughly, especially under load, to ensure the async API interactions are stable.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.