Java Reference
In-Depth Information
Imagine that you read the player's health as 50 in one thread, but then a
second thread sets it to 0—killing the player. You don't know that, and you
subtract 10 from the player's health and reset it to 40. Now the other thread
thinks it's killed the player, but instead of 0 the health has “magically” been
set to 40! That's a simple and innocent example, but far worse things can
happen that could cause strange bugs or make your code—and the server
—crash.
There are ways to write code that can be run by multiple threads safely;
however, many libraries, and most of the Canary API, are not designed that
way.
That's important enough to repeat: the Canary API, and our plugin code that
uses it, are not built to be run by multiple threads. The code will break.
So when we want to run a piece of code “later,” we can't actually let it run at
some random time. In particular, we can't let a piece of our code run at the
same time as another piece of our code, or at the same time as the server
code.
Instead, we have to let the server determine when to run the code. Then it
can run it pretty much as if it were a player typing in a command or
responding to an in-game event; it's the only thing running at the time. We
calls that a synchronous task, and that's what you'll learn how to set up in
this chapter.
But to set up a task, we'll first see how to make our own classes.
Put Code in a Class by Itself
First, let's be a little more precise in what we name things. In Java source
code, you declare a plugin to be a public class , which is Java's way of saying,
“This is a recipe. I can make objects of this class at runtime.” While I've been
loosely talking about recipes and parent recipes, I'm going to start calling
them by their proper Java name: classes . “Recipes” are classes.
So far we've sort of cheated—we've been putting all new code in our one plugin
class, in one source-code file. When the Minecraft server runs, it makes one
object from that class file and uses that.
But if you look at other plugins out on the Internet, you'll notice that often a
plugin (and larger programs) are made up of several different classes, all
working together. The main class file has the plugin itself, while other class
files might contain related objects, or tasks to be scheduled, or any other
kind of helper code that the plugin might need. We've been adding code right
 
 
Search WWH ::




Custom Search