I am not sure what the best solution for following situation is:
My Java-program is permanently reading from a tcp-stream. At the same time it is neccessary to persist these data to a database. The amount of data which should be written to the database could differ
I have read a lot of about message-queueing-systems and so on. In detail, my solution would consider using a LinkedBlockingQueue. Thereby, there are two threads: a) Starting a producer-threat which will perform reading from the tcp-stream b) Starting a consumer-threat which will write the (parsed) data from the stream to the database
The (example-)code looks like following:
Main.java
public static void main(String[] args) {
LinkedBlockingQueue queue = new LinkedBlockingQueue(50);
Producer producer = new Producer(queue);
Consumer consumer = new Consumer(queue, producer);
Produer.java
public class Producer implements Runnable {
private LinkedBlockingQueue queue;
private boolean running;
public Producer(LinkedBlockingQueue queue) {
this.queue = queue;
running = true;
}
@Override
public void run() {
//read TCP-Stream here and save parsed messages to queue
}
public boolean isRunning() {
return running;
}
Consumer.java
public class Consumer implements Runnable {
private Producer producer;
private LinkedBlockingQueue queue;
public Consumer(LinkedBlockingQueue queue, Producer producer) {
this.queue = queue;
this.producer = producer;
}
@Override
public void run() {
//insert data into database here
if(producer.isRunning()) {
//while producer is running, data needs to be inserted to database
}
}
Is this a solution you would recommend to use? Or do you know better solutions?
Thank you!