The API contains methods that are able to atomically increment a variable in the cache and decrement a variable. Effectively this means that these operations are safe for use by any client across the cluster at any time and there is some guarantee that these will be done in the right order. We will demonstrate these methods by tracking the total number of chat clients connected to the server.
Add the following lines to the Main method
after the connect method:
try { connect(serverAddress); register(); unregister(); client.shutdown(1, TimeUnit.MINUTES); } catch (IOException e) { e.printStackTrace(); }
Then add the following two methods to the end of the class:
private static boolean register() { userId = client.incr("UserId", 1, 1); System.out.println("You are user " + userId + "."); userCount = client.incr("UserCount", 1, 1); System.out.println("There are currently " + userCount + " connected."); return true; } private static void unregister() { client.decr("UserCount", 1); System.out.println("Unregistered."); }
These two methods demonstrate the use of the
incr and decr methods which
increment and decrement a variable, respectively. The application
you are building uses this to keep track of how many users are
currently running the program. This particular overload of the
incr method takes a default value which it will use if the key
UserCount does not exist, and will return the current count. In
this case the first user will be assigned user number 1. Finally,
when the unregister method is called, the decr method will be
called to subtract 1 from the UserCount value.
Finally, you must add the following static member variables to the top of the class:
private static long userId = 0; private static long userCount = 0;
If you compile and run this program now, you will see the following output:
Reconnected count: -1 You are user 1. Registration succeeded. There are currently 1 connected. Enter text, or /who to see user list, or /quit to exit.
Up to this point, the application is doing some very simple things, allowing a user to connect, and keeping track of how many users and currently connected. It's time to start adding some data to the system, and providing some methods to interact between multiple clients.