1.15.2 Need some help with async..

Discussion in 'Spigot Plugin Development' started by chmod_777, Mar 25, 2020.

  1. Im trying to implement async data handling in my code and I cannot get it to quite work. All of my data handling (mysql, sqlite, yaml for now) works flawlessly, at least to my knowledge, but I recently decided to allow them to run asynchronously.

    I started with flat file storage since its the easiest and most straight forward (Is there even any benefit to offloading flat file data off the main thread?), but for whatever reason I cannot get the FileConfiguration that is returned in the supplyAsync() to be assigned to an instance variable named 'data'. Because of this I'm thrown null pointers for obvious reasons.

    Here's the method:
    Code (Java):
    protected void returnFlatFile(String fileName) {
            CompletableFuture.supplyAsync(() -> {
                file = new File(plugin.getDataFolder().getPath(), fileName);
                if (!file.exists()) {
                    logger.log(Level.INFO, NEW_FILE);
                    try {
                        logger.log(Level.INFO, "Done.");
                    } catch (IOException e) {
                        logger.log(Level.SEVERE, IO_ERROR);
                return YamlConfiguration.loadConfiguration(file);
            }, plugin.getThreadPool()).thenAcceptAsync(config -> data = config, plugin.getThreadPool());

    I know I can:
    Code (Java):

    protected FileConfiguration returnFlatFile(String fileName) {
          CompletableFuture<FileConfiguration> complete = CompletableFuture.supplyAsync(() -> { ... });

          return complete.get() //Try catch(s) go here but I was too lazy to write it :P
    but I would rather avoid handling exceptions. That being said I still consider myself a newbie, so your judgement may be better than mine.

    Thanks in advance!
  2. Guys everywhere say that work with files in async is :sick: