Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Wednesday, March 11, 2015

Accessing databases through multiple threads



Most applications require store information. The options and scenarios are diverse. Let's focus on the scenario in which multiple remote clients need to store centralized information. No matter if the remote client is a standalone application, website or mobile app

   In general, it is not advisable to let the remote clients communicate with the database directly. It is always better to create a middleware to manage the persistence of the entire system. Not only for safety reasons but because we have a single point of entry to the database so that we can enhance and manage performance in a unified way.

So customers send and receive data from the server and he will be responsible for managing the persistence of this information. In small databases  with few connections, not much to worry about. With notions of SQL you can make a small server with good performance.

But when you are facing scenarios involving large numbers of users or large transactions, you must use more advanced techniques. There are two major problems to deal:

  •      Large number of users:

      This is more a question of architecture, but it is always good practice create a new thread for each new connection to a remote client. Of course, you have to limit the number of threads depending on your environment if you want to ensure quality to  everyone connected.
You cannot share the same connection with all the threads or rather, you can do but as database providers implement sessions  in a synchronized way, the commands will not be executed until their turn. You will be within a FIFO (first in, first out) queue.

The idea is to create a new database session for each external connection ( owned by the new thread). Each remote client will get or keep your data in parallel as if he just connected to the database.

So we're done ... isn’t it?

Unfortunately, this is not possible or at least not always. You can’t open a new  session for each incoming connection (and therefore the same number of threads) because sessions database are costly both in terms of resources and licenses (depending on how each provider licensing).

 The solution to this problem is to create a pool of database connections. Each thread will request a free connection pool when needed and released when he finishes what he has to do. Thus, each thread will not own a connection. Actually there is no sense to maintain a connection to the database without using. In short, each thread will request a connection when needed, will do the job, and then release the connection.

…but  it can still happen that when needed, there are no available  sessions  to the database in the pool. In this case, the thread waits until another thread release a database session. In this scenario, the user will likely experience some delay. If this happens frequently, you should ask if you can increase the number of sessions in the pool, or if we have reached the maximum capacity, purchasing more resources to enable your server to handle this load.

In relation to pool connections, there are some providers (providers including databases) that provide implementations that can be used via API. We have used some of them and they work quite well. You also have the option of making your own implementation. It will cost you some time, but on the other hand, you will have more control over what you do and you might particularize and optimize it as it suits us.

If you choose to do it yourself, a good idea is to open the database sessions when the server starts because  the creation of a database connection has a high cost. Therefore, if the connection is opened at start up, there will be no perception of the cost of establishing the connection for remote clients


  •   Long transactions or lot of queries / commands involved.

      There are other scenarios or mixed scenarios in which the issue is that you have to run a lot of queries for the same user request. The perception of the users is that your request takes longer than expected. How to deal with this?

Depends deeply on the scenario in which we find ourselves. In fact, to solve this problem requires insight into the performance of your application. We can use a similar strategy to that we used on the last point.

We will create a specific thread for each group of linked commands. Take an example, if you are reading data from a client and their orders, you can think of parallel load data from customer and every order, because, no apparent dependence. So, again, we will create different threads, requesting a connection to the pool, and run these commands in parallel. As a result of this approach, users will wait  only the slowest group of commands that are executed in parallel.

If a branch is heavier than the rest, we can choose to return part of the data while the heavier parts are still running. If you do this, the remote client will need to know in order to inform the user about it. At the end of the heavier parts, send the information to the client so that you can complete the user request.

This approach has some risks that you need to know:

    1.   You will  deal with some threads in parallel, so you are in charge of joining together when they finish their duties. Be careful because you have to ensure that the information you are accessing is already loaded. Use semaphores or other mutual exclusion mechanism to control access to these areas.  
    2. Beware of deadlocks that can cause connection pool usage. Release the session as long as you do not need it. For example, if you create a new thread from another thread already has a session, the latter may end up locked (depending on the size of the pool and context). You could be waiting for her son before releasing your session while he is also waiting for an  available session. If this behavior is widespread we could have a global lock the entire application. This scenario may seem unlikely, but possible oop often suffer this problem. To address this, as mentioned, let's release the database session when we don't need anymore. But be careful, when dealing with hierarchies of objects and multithreading is not as straightforward ensure this behavior. A simple solution is to restrict parallel to the objects that have no dependency downwards. In a graph of tree , we would only  put in parallel the leaves because they have no dependencies.
Combining this two techniques you can get a good performance on your intensive database access applications.



Tuesday, March 3, 2015

Building Mobile Games Using the MVC Pattern



When we first decide to create any application we have to keep in mind that our app can be ported or migrated to other platforms. Maybe we will never have to do it but keeping this in mind we will create a better app. So we will need a good layer design to get this goal. A good way is to follow the MVC (model view controller) paradigm. In a few words:

  • Model: The logic that remains under any application. Also known as Business Rules.
  • View: The tier that paints to the screen.
  • Controller: The middle layer that connects Model and View and handles user events by calling the model and displaying to the screen to the View layer.

Keeping these layers separated will allow you to switch your UI framework with less changes than expected.
If we think in terms of oop, we can  implement this architecture  by creating interfaces between view and controller layers. This will force you to keep this model and avoid the temptation to mix these layersIf you are able to abstract the view layer, it will be easier to implement an application based on the MVC architecture

For instance, look at our view interface that we are using to develop our remote client in our   multiplayer game: “Snake the net”…

public interface ClientNibbles {
 public void getSet();
 public void go ();
 public void update (Board game);
public Movement getMovementDirection();
 public int getPlayerId();
 public int getIdGame();
 public int getnumPlayerGame();
public void setPlayerId(int id);
 public void setIdGame(int idGame);
 public void setnumPlayerGame(int NumPlayerGame);
}

There is actually two main operation to implement: update method and getMovementDirection .  We send, each tick, to the view layer a board object with the position of each players. The view layer just needs to read this object and paint a representation of it to the screen.  The Controller and model layers just deal with the server which movements to do but, once commited, they just send a “photo” to the view layer in order to paint the screen. In the reverse way, the controller layer will get own movements by calling getMovementDirection (). The rest of the interface defines control method to configure an incoming game. I think that is an exciting and simple approach. Isn’t it?

If we follow this proposal of architecture we will just need to port the upper (view) layer in some scenarios. In detail:

Our game is intended to be, at first, an Android game. Therefore, we only have the option of using Java as a programming language. You could be tempted to go to Android Studio (or ADT) and start right away. Wait a minute… Test and debug a mobile game is always more complex compared to an standalone app. Thus, basing on our MVC model, we will make fisrt  a standalone  application, fix bugs and once we have stabilized we will just write the part of android view. Think what you will get:
·        
  •        Keeping just one source of the code (Controller and logic).
  •       Once developed the project in Android, if we detect incidents related to the core It’s easier to come back to standdalone platform to find out the problem instead of using android. Then once  fixed the error, we would  check that everything is ok at mobile scope.

 In our app, we started by implementing a standalone client that implemented the interface defined at view level. This allow us to test the model layer without using any mobile device or simulator, just simple java client apps. By doing this, we are also creating an pure Java game that can be played by his own.


Once stabilized we just need to implement the defined interface (view layer) at android scope. We created dedicated activities, layouts and event custom views to handle this.  Once done, we are able to test the game using two different types of clients: swing java and android clients.

Tests with different remote clients(Java(Android)
But above all, we have to recall that we are designing a multiplayer game. It will be a game that needs someone to accept or discard the movements done by each movement. The asynchronous approach (peer to peer) won’t work since we need someone to decide if a remote movement is on time or late and if we let the clients decide this acceptance or not, it can produce different games in each client… and this would be a disaster. So, we need a mandatory server to handle this. And a server has clients…

So, actually, we have two components to implement: client and server. We also decided to separate these components through interface contracts. So once implemented the server side and deployed where we decided we wouldn't need to change anything (lifecycle apart). While each part implements his side everything will be OK.


Let's turn back at the client side. There are some theories that tell us that remote players in multiplayers games should be  something like a thin client. This means that each client will wait until the server sends the players movement message to paint into the screen. You can imagine how laggy will be perceived by the user. To improve this scenario, and overcome   the perceived latency we decided that clients are going to predict his own movements. We will implement a mandatory server and a client who makes predictions. (The server consolidates and send back to each client the  consolidated movements for each tick.). By doing this, every client can’t move on his own (or almost).


Andoid client screenshot

So the client won't be a thin client. He may also needs to play. Actually, he needs to have the same logic that the server so we will share  the logic code, or almost, by the client and the server. Again we will share the model code between client and server.

There are just Two differences with the server:
  • The client does not consolidate any movement. He just makes his own prediction and moves his own players. He will move the rest of  players once received the consolidated movements by the server
  • If we are wrong in our prediction we will get back to the last tick  and we will replay our own movement based on the server information.


To deal with these differences you  just need to  create an additional layer in order to handle these differences without affecting the common part.

Thursday, February 19, 2015

First Footage


It’s time to make our dreams come true. We have been writing some tech entries about how to do a multiplayer game. Now, you can see how  we have implemented this ideas . Look at the following video: 4 players/snakes online trying to survive:






You can detect easily some client time tick corrections (just notice that client tick is not always the same). In the other hand, it’s not easy to detect that there is one correction at client side. During the game, one movement arrives late to the server so when the consolidated server movements gets back to the client, he’s forced to correct the initial prediction and moves based on server movements. As a user, you will see how an initial movement is quickly modified(our head changes his position).

The best of all is that everything works in a smooth way.

Monday, February 2, 2015

About the game: Snake The Net



We have focused on tech issues and specialized  details about multiplayer games and we have not explained anything about "Snake the net", the game that we are designing.

It's all about several snakes that try to kill the other ones while avoiding other obstacles. Does it sound familiar? Yeah, i agree... we are not reinventing the wheel...or maybe we are. Le me explain.
We won't convince no one that this is an original game. Of course, tens of games are based on the same idea. But, do you know any snake multiplayer game? Even Better. Do you know any snake multiplayer game fast enough to deserve be played?  I don't think so.


Our challenge is to make a multiplayer game with ticks (turns) below 500 ms. I think 300 ms will be such a challenging objective. Consider this: Players around the world will play at the same time and they have to see, obviously, the same game.

About the game itself we have made some new variations.  Several basic rules:

We are a snake ;-) Nothing new. Isn't it?

This is a piece of wall. We can't move inside a wall. If we do, we die and we become also a sequence of walls. Thrilling.


And, we have designed some magic cells that you can eat:

Get Bigger. We grow as much as the number displayed at the toolbar


Go Fast. If we eat this cell, we start moving twice as normal. We only move several ticks, depending on the number displayed at the toolbar.



Stop Other Players. We freeze the other players while we move smoothly. As usual, it depends on the number displayed at the toolbar.



Decrease Rivals size. The reverse of the last cell. If you eat it, the other players will decrease their size .




The game implementation is quite advanced  but we are facing now the exhausting  duty of testing it. The hardest part, as you can imagine, is related to networking issues, since this game shines by the multiplayer layer.

Of course, if no one connects at a time, you still would play because the server will create some bots... At the moment they are not so intelligent, but they will be... soon.



Anyway, you can see the first screenshots published. In the following posts, it will be available a video where you will see the gameplay.


Enjoy it!





Monday, January 5, 2015

Mixing TCP and UDP to reduce latency in real-time connections.


Let’s start to use our best cards to deal with latency issues. Remember that previously (last entry) we chose to implement all dialogs between client and server based on TCP protocol. We also deactivated Nagle’s, algorithms among other strategies, that caused our app to experience high latencies.

      We have to make a step forward.

TCP packet delivery control adds  extra unknown sized traffic between client and server that we will pay with lack of gameplay. Every packet has to be acknowledged by the receiver and, in case of data lost, a new packet will be send with its consequent acknowledge. It's easy to understand  how this data interchange can impact in our mission to be fast.

So, let’s think about what kind of traffic we are sending  between client and server?. Can we tolerate some packet lost?. 

Basically, analyzing almost every game,  we have two kind of commands:
1.     The Commands that exchange client and server in order to configurate how the game will be (and prepare it before it starts) must be synchonized. We have to assure that we respect the order sequence described in our interface contract between client and server (see last entry). For example, We can’t pay a drink if we have not already ordered. At this time, the game has not began and it’s not critical if we experience additional delayed milliseconds. So we can and should keep using tcp protocol to implementing these commands. We can fully enjoy TCP packet deliver control since it doesn’t matter at all some little delay.

2.     The Commands inside a game need to be quick. It would seems quite obviously but once inside a game every millisecond saved worths a penny. We will be dealing with ticks about half a second because noone would play our game if we see our snake moving fast as a truck. We have to squeeze our brain to get this part of the game as fast as possible keeping on mind that we are playing across internet. This means different lag from players, changing player latency  during the game and  Players leaving the game once started.

Gathering these premises, it seems clear that we need to keep under control what we really send throught the net. So, we  have to avoid sending extra packets as our main objective… and which protocol is sending extra packets out of our control? TCP.
We need to avoid tcp acknowledge traffic that is generated by TCP deliver control packet. By doing this, we will reduce some data traffic but we will loose also the guarantee that packets are going to arrive at time and at the order that we sent from the other point.
In other words, we are going to use UDP wherever we can and add some extra functionality to guarantee order and delivery issues that we need during the game.

Focusing on those commands related to the game itself there are two kind of subcommands:

1. List of movements consolidated by the server:

Keep on mind that the server is imperative and is in charge of guarantee that every client has the same view of the game. So, we decided to send, once every tick ends, a message containing all the movements consolidated by the server. With this message, the remote client will move non own players and will check if his anticipated movement can be confirmed. If we are lucky, everything is ok but if the remote client movement does not arrive or arrive to the server once the tick is ended we may be in troubles. In fact, we will face with remote/server inconsistencies if the remote client has changed the movement direction because the server won’t realize and the server will have sent back a movement with no change direction.  This means that the remote client will be forced to move back to the last tick scenario and move again based on server moments.

This means that we have to implement some movement buffer mechanism to allow this movement back described above. It also  means that we have no alternative except keep using TCP protocol. This messages has to arrive to the remote clients  sorted and every tick (we can allow certain delay). Otherwise, we would have to implement packet delivery control because it matters the order of list of movements and specially because it would make by far more complex  the implementation of the movement back algorithm. Let’s think how would we do if we can't assure that every tick will receive a confirmation of our predictions.

Yes, you may think, let's send the whole game board every tick. This means more and more data to send and that is one of rules that we can’t break .In fact, remember that we move non own players once list of movements are read by the client. So, the worst thing we can expect is some addicional lag between own player and other remote players.

2. Movement command that the client sends to the server:

Maybe the most important command that we need to be quick is the movement sent by the client to the server. It have to arrive before the server closes the turn tick. So, every movement received later is discarded and it will be used current direction to make the player server movement. This, as describes before,  will produce an ammendment to the remote client that is late once he gets the summarized message sent by the server. This discard issue it’s pretty the same as loosing  a client movement message. So we can use the same strategy.

The main idea is that a
 client message late can be considered as a client message lost. So we don’t care at all if it’s acknowledged by the server. We only want to arrive early. The acknowledge is implicit by the consolidated server movements that the server will send once the tick ends. So, we got it. We have made our custom delivery control message and this means that we don’t need and we don’t want TCP Protocol.

Let’s use UDP protocol for this commands. By doing this, clients are going to arrive sooner so it means that less movements are going to be rejected. This will allow us to reduce server tick time and we will get a faster game!!! In the other hand, we will loose some packets but we  will reduce at the minimum expression the lag between client and server that’s is our main goal.


So summarizing, we finally will use a
 mixed combinations of protocols to keep our net dialogue coherent and a fluid online game with little gap between server and client.