Hello, I'm wondering if it's possible to run a code that will return a string value asynchronously from a certain URL. The server hangs noticeably when I try to get a CSV from it, so I don't think running it in the main thread is very efficient. Here is what I have now: Code:java public String getData(String symbol) throws MalformedURLException, IOException { String bid = null; InputStream input = null; Reader reader = null; input = new URL("blah blah url"+symbol).openStream(); reader = new InputStreamReader(input, "UTF-8"); CSVReader info = new CSVReader(reader); bid = info.readNext()[0]; info.close(); return bid==null ? "Error" : bid; } Any suggestions on how to make this more efficient?
Hydrosis Start a new Thread for it. PHP: private class Task extends Thread{ public void run() { // Do your code here }}new Task().start();
xTrollxDudex is right, you should use a new thread for this. Although I'd recommend to use Bukkit API for this. The problem is that your code example cannot be easily transformed into a new thread because a thread will not return String. You need to begin earlier. Code:java Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override public void run() { String data = getData(symbol); // do something with data here }}; In an async task you are not allowed to use Bukkit API. That means you should not change blocks, teleport players etc. This can crash your server. If you want to access Bukkit API again you need to run a sync task again. Code:java Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override public void run() { final String data = getData(symbol); Bukkit.getScheduler().runTask(plugin, new Runnable() { @Override public void run() { // you are allowed to access API here } }); }}; data has to be final then to be accessible inside the new task. So has every other outer variable to be if you need to access them from inside a task.
xTrollxDudex How could I use that to return a value (such as a string)? Could you type a quick example of that? AmShaegar Thanks, that works for me!
Hydrosis You could do what AmShaeger did or you can use a reference String each time a new Task is created, if you do use this method, make sure to lock down the field before setting it.