1.12.2 Caching a "mode"

Discussion in 'Spigot Plugin Development' started by Fabio030, Mar 21, 2020.

  1. Hello everyone.
    I'm making a plugin that when i type /staff it enables me the "staff mode", and when i type /staff again the plugin disables me the "staff mode".
    To do that i need a cache.
    So my question is: How can i make a cache?
    Can you provide me an example?
  2. Choco


    You should be quite familiar with Maps and their implementations by this point. You'll want a Map<UUID, WhateverConstantForYourModes>. Alternatively, if you just have a staff mode, a Set<UUID> will suffice.
    • Agree Agree x 1
  3. In addition to this, if you want these values to retain on server restart you'll need to store them in some kind of database and recreate the Map or Set.
    • Agree Agree x 1
  4. So maps preserve their values?
  5. Choco


    No. See above.
    Nothing you hold in memory is going to persist. You have to write it to file and read it again on startup (or when queried when required, whatever, but for modes it's best loaded into memory again)
  6. I mean. Maps preserve their values even if the function ends to execute? Or i have to make it protected?
  7. Choco


    If it's a field, sure. A basic understanding of how the language works is expected before attempting to write plugins.
  8. I never user Maps. Can you make me an example class?
  9. Code (Java):

    private Map<String, Boolean> theMap = new HashMap<>();

    // to set
    theMap.put(”a string”/*this is a key*/,true/*this is a value*/);
    // to get
    // for example, theMap.get(“a string”); will return true
    // to remove
    /* a map can contain any object in either value or key but cannot contain primitives */
  10. I know, this is only an example. But instead of using a Map<String, Boolean>, using a Set<String> and Set#contains(String) would be cleaner.