I am writing a Server using Java NIO that will receive data from client (for eg. location) and will store the data into a database using Microsoft SQL Server 2012.
I know the call to database is blocking and thus writing codes in the main NIO thread will be to kill all the benefits of NIO.
So how should I proceed?
Another thread to process database requests but how will I send requests to that thread and how will it store them(queue ?) ?
Edit : If anyone suggest using asynchronous DB , please tell one which has good documentation and is supported with java and Microsoft SQL server.
Preferably will like to use JDBC.
Any help will be appreciated.
If you want to decouple receipt of information to storage in the database then a queue is the normal approach.
Note that all your a really doing is improving response time (deceasing latency) and adding the ability to buffer input to flatten out spikes in the request load. The actual rate at which you can transfer data to the database (throughput) will be the same.
You can use one of the Java
BlockingQueue
implementations injava.util.concurrent
. These are thread safe.However, if you system goes down you will lose any requests in the queue. If that is not acceptable you will need to use a JMS implementation that gives you persistent queues, but you might find that writing to the queue is as slow as writing to the database.
I would first verify whether you really need this decoupling though. The databases are usually pretty fast. You could try reducing the frequency of commits, but again, there is a risk of loss or inconsistency of data.