Again and again I encounter a similar problem: there is a part of the code that processes the data as it arrives from the user / network / produces some kind of. For reasons of efficiency, I don’t want to name flush()or commit()for each piece of data that I receive, but only occasionally.
I usually come up with this code:
class Processor {
private final static MAX_SAVE_PERIOD = 60000;
private final static MIN_SAVE_PERIOD = 20000;
private final static int MAX_BUFFER = 10000;
Arraylist<Data> dataBuffer = new Arraylist<Data>();
private long lastSave = 0;
public Saver() {
new Timer().schedule(new TimerTask() {
periodicSave();
}, MAX_SAVE_PERIOD, MAX_SAVE_PERIOD);
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
periodicSave();
}
}));
}
public synchronized void processData(Data data) {
dataBuffer.add(data);
if(dataBuffer.size() >= MAX_BUFFER) {
saveData();
}
}
private synchronzied void periodicSave() {
if(!dataBuffer.isEmpty()) {
saveData();
}
}
private void saveData() {
if (System.currentTimeMillis() - lastSave < MIN_SAVE_PERIOD) return;
...
lastSave = System.currentTimeMillis();
}
}
It seems to me that I reinvent the wheel every time I write this, and what else, I constantly change things every time I write such code, depending on whether the different parts make sense in a particular context.
, , , . , , . , !
. , , , JVM , . , - , , MIN_SAVE_PERIOD , , , saveData. .