I'm creating a game with a server and multiple clients. I'm using Kryonet for networking and each connection has it's own listener where it receives packets.
There listeners are called on a background Kryonet thread and I can't block them cause it would affect all of the users.
I have created my database, configured a ConnectionPool in a synchronized Singleton class:
private static final BasicDataSource dataSource = new BasicDataSource();
static {
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://111.111.111.111/db");
dataSource.setUsername("server");
dataSource.setPassword("serverpass");
}
public Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
and now I need to execute some queries. Here comes my issue. As we know, query could take long to return a result so it's totally unacceptable to execute it on a 'Kryonet' thread (when packet is received). For example, when user sends his 'RegistrationPacket' I need to make a query to the database and return him a result within a packet. When I receive the packet, I need to put it in background and from there - send result to the client.
Here comes my question: How to handle making database queries in background using Java?
Should I use Executors? Threads? As I know opening a Thread for each connection is a bad idea, (cause 200+ workers).equals(disaster). If someone could help me I would be grateful! :)