user161607
user161607

Reputation: 21

Issue while handling database connection in Multi-threaded Server - Java

I have created a Java based server which will listen for data from clients. As the server receives data , it has to parse it & update it in Database. Client sends data very frequently say every 2-3 seconds & number of clients can be from 200-1000. What I have done is Server is Continuously listening for data from client. As it receives data, it starts a new thread(will be separate thread for each client) which parses data & updates it in database. I am using only one connection with database for updating information of each client.
Issue is sometimes previous request is not completed & another request is sent by client which go on increases for other clients also as I am using same database connection for all clients.

I need suggestion to improve performance that whether I should create separate connection for each client OR else what should I do ?

Editted :- Anybody please help with the code. Say If I am dealing with the 600-700 client sending data & creating separate thread for each client upon request & then breaking it .then what should be my database pool size ?. More threads are also running parallel which makes connection with database. May I need to wait If client data is being processed. But In my case I can not hold client data. How do I handle this? Please suggest.

Upvotes: 2

Views: 803

Answers (2)

11thdimension
11thdimension

Reputation: 10653

You have to use poolable connections for database and a thread pool to go with it.

For poolable connection you can use Apache DBCP, check out configuration options
Below is example usage

BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(JDBCDriver);
ds.setUrl(JDBCUrl);
ds.setUsername(JDBCUser);
ds.setPassword(JDBCPassword);
ds.setInitialSize(initSize);
ds.setMaxTotal(maxTotal);//negative for no limit
ds.setTestOnBorrow(false);
ds.setTestWhileIdle(true);

Connection con = ds.getConnection();

For thread pool you can use ExecutorService

It has following methods

execute(Runnable)
submit(Runnable)
submit(Callable)
invokeAny(...)
invokeAll(...)

Following is sample usage

ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(new Runnable() {
    public void run() {
        System.out.println("Asynchronous task");
    }
});

Now no matter how many Runnables are submitted to ExecutorService it runs only 10 at a time.

Upvotes: 0

Aman gupta
Aman gupta

Reputation: 39

Create a pool of connections beforehand. Whenever a new request comes, provide a connection that is free, to that request. This way, you will not be connecting/disconnecting dynamically, and still get a connection availability.

Upvotes: 1

Related Questions