Hello, since I'm not very experienced with threads I hope that someone can tell & explain me how the best solution for the following problem would look like: We need to save the homepoints (warps) of our players in a mySQL-Database and I would like to only read in those points if necessary. So if a players joins I want to load the homes and if he disonnects I want to delete them (from RAM).. now I found out that connecting to the database in the mainthread or other synchronised threads is a bad idea since it causes the server to lag if the connection is bad or failed. Here is my idea but of course I don't know if this is a possible and/or good solution: Main Thread: Putting new players into a List A Asynchronous Thread (Ticks every 1-2secs): Take players from A and try to receive any data from my database and put the results into either a success-list (A) or a failed-list (B). Synchronsous Thread (Ticks every 1-2sec)s: Take look at those two lists and do stuff with the players Because I want to learn it would be cool if you really explain why those things might do no sense. Also I'm willing to read any links that really help me since I already found a lot of stuff about threads that doesn't really help with this "problem". Thx
Just put the method that loads the player homes from the database in a async thread. Example Code: public void loadWarps(final Player p){ asyncthread stuff{ mysql stuff here } } That would be way easier then having to deal with lists and what not.
Yes but is it okay to start a new thread everytime someone joins? I heared that creating new threads everytime is not very efficient so I thought about working with a kind of queue for a repeating thread/task.
No I wouldn't recommend creating a new thread every time as that could use unnecessary resources. Rather I'd suggest you make a private HashSet inside your load warps class, with a public method to add and remove from that list and then check your async thread against player names in the HashSet.
Get result set from db on plugin load, store the data in RAM and when you need to change data just execute query and update local data in RAM. Remember that only opening connection is lagging.
Based on what you have said the simplest solution is to use a single asyncthread, list and a new class/struct that takes a string (username) and enum (what you wish to do to this username). You set the async thread running so that it locks the list, copies the contents to a local list and then clears the list and releases the lock. The async thread will then crunch the requests in the local list. Having the thread do this every second will be more than enough. This will be threadsafe and flexible enough for you to do whatever you need without compromising on performance.