• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

wz2cool / local-queue / #42

03 Feb 2025 03:03AM UTC coverage: 91.02% (-0.9%) from 91.958%
#42

push

wz2cool
change locker

36 of 42 new or added lines in 2 files covered. (85.71%)

5 existing lines in 1 file now uncovered.

598 of 657 relevant lines covered (91.02%)

0.91 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

87.1
/src/main/java/com/github/wz2cool/localqueue/impl/SimpleProducer.java
1
package com.github.wz2cool.localqueue.impl;
2

3
import com.github.wz2cool.localqueue.IProducer;
4
import com.github.wz2cool.localqueue.event.CloseListener;
5
import com.github.wz2cool.localqueue.helper.ChronicleQueueHelper;
6
import com.github.wz2cool.localqueue.model.config.SimpleProducerConfig;
7
import com.github.wz2cool.localqueue.model.message.InternalWriteMessage;
8
import net.openhft.chronicle.core.time.TimeProvider;
9
import net.openhft.chronicle.queue.ChronicleQueue;
10
import net.openhft.chronicle.queue.ExcerptAppender;
11
import net.openhft.chronicle.queue.RollCycle;
12
import net.openhft.chronicle.queue.impl.single.SingleChronicleQueue;
13
import org.slf4j.Logger;
14
import org.slf4j.LoggerFactory;
15

16
import java.io.File;
17
import java.io.IOException;
18
import java.nio.file.Files;
19
import java.time.LocalDate;
20
import java.time.format.DateTimeFormatter;
21
import java.util.ArrayList;
22
import java.util.List;
23
import java.util.UUID;
24
import java.util.concurrent.*;
25
import java.util.concurrent.atomic.AtomicBoolean;
26

27
/**
28
 * simple writer
29
 *
30
 * @author frank
31
 */
32
public class SimpleProducer implements IProducer {
33

34
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
1✔
35
    private final RollCycle defaultRollCycle;
36
    private final TimeProvider timeProvider;
37
    private final SimpleProducerConfig config;
38
    private final SingleChronicleQueue queue;
39
    private final LinkedBlockingQueue<InternalWriteMessage> messageCache = new LinkedBlockingQueue<>();
1✔
40
    // should only call by flushExecutor
41
    private final ExcerptAppender mainAppender;
42
    private final ExecutorService flushExecutor = Executors.newSingleThreadExecutor();
1✔
43
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
1✔
44
    private final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
1✔
45
    private final ConcurrentLinkedQueue<CloseListener> closeListeners = new ConcurrentLinkedQueue<>();
1✔
46

47
    private final AtomicBoolean isFlushRunning = new AtomicBoolean(true);
1✔
48
    private final AtomicBoolean isClosing = new AtomicBoolean(false);
1✔
49
    private final AtomicBoolean isClosed = new AtomicBoolean(false);
1✔
50
    private final Object closeLocker = new Object();
1✔
51

52
    public SimpleProducer(final SimpleProducerConfig config) {
1✔
53
        this.config = config;
1✔
54
        this.timeProvider = ChronicleQueueHelper.getTimeProvider(config.getTimeZone());
1✔
55
        this.defaultRollCycle = ChronicleQueueHelper.getRollCycle(config.getRollCycleType());
1✔
56
        this.queue = ChronicleQueue.singleBuilder(config.getDataDir())
1✔
57
                .rollCycle(defaultRollCycle)
1✔
58
                .timeProvider(timeProvider)
1✔
59
                .build();
1✔
60
        this.mainAppender = initMainAppender();
1✔
61
        flushExecutor.execute(this::flush);
1✔
62
        scheduler.scheduleAtFixedRate(() -> cleanUpOldFiles(config.getKeepDays()), 0, 1, TimeUnit.HOURS);
1✔
63
    }
1✔
64

65
    private ExcerptAppender initMainAppender() {
66
        return CompletableFuture.supplyAsync(this.queue::createAppender, this.flushExecutor).join();
1✔
67
    }
68

69
    // region flush to file
70

71
    private void stopFlush() {
72
        isFlushRunning.set(false);
1✔
73
    }
1✔
74

75
    private void flush() {
76
        while (isFlushRunning.get() && !isClosing.get()) {
1✔
77
            flushMessages(config.getFlushBatchSize());
1✔
78
        }
79
    }
1✔
80

81
    private final List<InternalWriteMessage> tempFlushMessages = new ArrayList<>();
1✔
82

83
    private void flushMessages(int batchSize) {
84
        try {
85
            logDebug("[flushInternal] start");
1✔
86
            if (tempFlushMessages.isEmpty()) {
1✔
87
                // take 主要作用就是卡主线程
88
                InternalWriteMessage firstItem = this.messageCache.poll(config.getFlushInterval(), TimeUnit.MILLISECONDS);
1✔
89
                if (firstItem == null) {
1✔
90
                    return;
1✔
91
                }
92
                this.tempFlushMessages.add(firstItem);
1✔
93
                // 如果空了从消息缓存放入待刷消息
94
                this.messageCache.drainTo(tempFlushMessages, batchSize - 1);
1✔
95
            }
96
            doFlushMessages(tempFlushMessages);
1✔
97
            tempFlushMessages.clear();
1✔
98
        } catch (InterruptedException ex) {
×
99
            Thread.currentThread().interrupt();
×
100
        } finally {
101
            logDebug("[flushInternal] end");
1✔
102
        }
1✔
103
    }
1✔
104

105
    private void doFlushMessages(final List<InternalWriteMessage> messages) {
106
        synchronized (closeLocker) {
1✔
107
            try {
108
                logDebug("[flushMessages] start");
1✔
109
                if (isClosing.get()) {
1✔
NEW
110
                    logDebug("[flushMessages] producer is closing");
×
NEW
111
                    return;
×
112
                }
113

114
                for (InternalWriteMessage message : messages) {
1✔
115
                    long writeTime = System.currentTimeMillis();
1✔
116
                    message.setWriteTime(writeTime);
1✔
117
                    mainAppender.writeBytes(message);
1✔
118
                }
1✔
119
            } finally {
120
                logDebug("[flushMessages] end");
1✔
121
            }
1✔
122
        }
1✔
123
    }
1✔
124

125
    // endregion
126

127

128
    @Override
129
    public boolean offer(String message) {
130
        return offer(null, message);
1✔
131
    }
132

133
    @Override
134
    public boolean offer(String messageKey, String message) {
135
        InternalWriteMessage internalWriteMessage = new InternalWriteMessage();
1✔
136
        internalWriteMessage.setContent(message);
1✔
137
        String useMessageKey = messageKey == null ? UUID.randomUUID().toString() : messageKey;
1✔
138
        internalWriteMessage.setMessageKey(useMessageKey);
1✔
139
        return this.messageCache.offer(internalWriteMessage);
1✔
140
    }
141

142
    /**
143
     * get the last position
144
     *
145
     * @return this last position
146
     */
147
    public long getLastPosition() {
148
        return this.queue.lastIndex();
1✔
149
    }
150

151
    // region close
152

153
    /**
154
     * is closed.
155
     *
156
     * @return true if the Producer is closed, false otherwise.
157
     */
158
    @Override
159
    public boolean isClosed() {
160
        return isClosed.get();
1✔
161
    }
162

163
    @Override
164
    public void close() {
165
        synchronized (closeLocker) {
1✔
166
            try {
167
                logDebug("[close] start");
1✔
168
                if (isClosing.get()) {
1✔
169
                    logDebug("[close] is closing");
×
170
                    return;
×
171
                }
172
                isClosing.set(true);
1✔
173
                stopFlush();
1✔
174
                if (!queue.isClosed()) {
1✔
175
                    queue.close();
1✔
176
                }
177
                flushExecutor.shutdown();
1✔
178
                scheduler.shutdown();
1✔
179
                try {
180
                    if (!scheduler.awaitTermination(1, TimeUnit.SECONDS)) {
1✔
181
                        scheduler.shutdownNow();
×
182
                    }
183
                    if (!flushExecutor.awaitTermination(1, TimeUnit.SECONDS)) {
1✔
184
                        flushExecutor.shutdownNow();
×
185
                    }
186
                } catch (InterruptedException e) {
×
187
                    scheduler.shutdownNow();
×
188
                    flushExecutor.shutdownNow();
×
189
                    Thread.currentThread().interrupt();
×
190
                }
1✔
191
                for (CloseListener closeListener : closeListeners) {
1✔
192
                    closeListener.onClose();
1✔
193
                }
1✔
194
                isClosed.set(true);
1✔
195
            } finally {
196
                logDebug("[close] end");
1✔
197
            }
1✔
198
        }
1✔
199
    }
1✔
200

201
    @Override
202
    public void addCloseListener(CloseListener listener) {
203
        closeListeners.add(listener);
1✔
204
    }
1✔
205

206
    private void cleanUpOldFiles(int keepDays) {
207
        if (keepDays == -1) {
1✔
208
            // no need clean up old files
209
            return;
1✔
210
        }
211
        logDebug("[cleanUpOldFiles] start");
1✔
212
        try {
213
            // Assuming .cq4 is the file extension for Chronicle Queue
214
            File[] files = config.getDataDir().listFiles((dir, name) -> name.endsWith(".cq4"));
1✔
215
            if (files == null || files.length == 0) {
1✔
216
                logDebug("[cleanUpOldFiles] no files found");
1✔
217
                return;
1✔
218
            }
219
            LocalDate now = LocalDate.now();
1✔
220
            LocalDate keepStartDate = now.minusDays(keepDays);
1✔
221
            for (File file : files) {
1✔
222
                cleanUpOldFile(file, keepStartDate);
1✔
223
            }
224
        } catch (Exception ex) {
×
225
            logger.error("[cleanUpOldFiles] error", ex);
×
226
        } finally {
227
            logDebug("[cleanUpOldFiles] end");
1✔
228
        }
1✔
229
    }
1✔
230

231

232
    private void cleanUpOldFile(final File file, final LocalDate keepDate) throws IOException {
233
        String fileName = file.getName();
1✔
234
        String dateString = fileName.substring(0, 8);
1✔
235
        LocalDate localDate = LocalDate.parse(dateString, this.dateFormatter);
1✔
236
        if (localDate.isBefore(keepDate)) {
1✔
237
            Files.deleteIfExists(file.toPath());
1✔
238
            logDebug("[cleanUpOldFile] Deleted old file: {}", file.getName());
1✔
239
        }
240
    }
1✔
241

242
    // endregion
243

244
    // region logger
245
    private void logDebug(String format, String arg) {
246
        if (logger.isDebugEnabled()) {
1✔
247
            logger.debug(format, arg);
×
248
        }
249
    }
1✔
250

251

252
    private void logDebug(String format) {
253
        if (logger.isDebugEnabled()) {
1✔
254
            logger.debug(format);
×
255
        }
256
    }
1✔
257

258
    // endregion
259
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc