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

wz2cool / local-queue / #41

02 Feb 2025 03:13PM UTC coverage: 91.958% (+0.2%) from 91.757%
#41

push

wz2cool
use atomic instead of volatile

105 of 124 new or added lines in 4 files covered. (84.68%)

2 existing lines in 2 files now uncovered.

606 of 659 relevant lines covered (91.96%)

0.92 hits per line

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

88.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
import java.util.concurrent.locks.Lock;
27
import java.util.concurrent.locks.ReentrantLock;
28

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

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

50
    private final AtomicBoolean isFlushRunning = new AtomicBoolean(true);
1✔
51
    private final AtomicBoolean isClosing = new AtomicBoolean(false);
1✔
52
    private final AtomicBoolean isClosed = new AtomicBoolean(false);
1✔
53
    private final Object closeLocker = new Object();
1✔
54

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

68
    private ExcerptAppender initMainAppender() {
69
        return CompletableFuture.supplyAsync(this.queue::createAppender, this.flushExecutor).join();
1✔
70
    }
71

72
    // region flush to file
73
    private void flush() {
74
        while (isFlushRunning.get() && !isClosing.get()) {
1✔
75
            flushMessages(config.getFlushBatchSize());
1✔
76
        }
77
    }
1✔
78

79
    private void stopFlush() {
80
        isFlushRunning.set(false);
1✔
81
    }
1✔
82

83
    private final List<InternalWriteMessage> tempFlushMessages = new ArrayList<>();
1✔
84

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

107
    private void flushMessages(final List<InternalWriteMessage> messages) {
108
        try {
109
            logDebug("[flushMessages] start");
1✔
110
            internalLock.lock();
1✔
111
            if (!isFlushRunning.get() || isClosing.get()) {
1✔
112
                return;
×
113
            }
114

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

126
    // endregion
127

128

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

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

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

152
    // region close
153

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

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

204
    @Override
205
    public void addCloseListener(CloseListener listener) {
206
        closeListeners.add(listener);
1✔
207
    }
1✔
208

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

234

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

245
    // endregion
246

247
    // region logger
248
    private void logDebug(String format, String arg) {
249
        if (logger.isDebugEnabled()) {
1✔
NEW
250
            logger.debug(format, arg);
×
251
        }
252
    }
1✔
253

254

255
    private void logDebug(String format) {
256
        if (logger.isDebugEnabled()) {
1✔
NEW
257
            logger.debug(format);
×
258
        }
259
    }
1✔
260

261
    // endregion
262
}
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