|
2 | 2 |
|
3 | 3 | import java.util.HashSet;
|
4 | 4 | import java.util.Set;
|
5 |
| -import java.util.concurrent.ArrayBlockingQueue; |
6 |
| -import java.util.concurrent.BlockingQueue; |
7 |
| -import java.util.concurrent.ExecutorService; |
8 |
| -import java.util.concurrent.RejectedExecutionException; |
9 |
| -import java.util.concurrent.ThreadPoolExecutor; |
10 |
| -import java.util.concurrent.TimeUnit; |
| 5 | +import java.util.concurrent.*; |
11 | 6 |
|
12 | 7 | import org.jabref.model.database.BibDatabaseContext;
|
13 | 8 | import org.jabref.model.database.event.AutosaveEvent;
|
|
26 | 21 | public class AutosaveManager {
|
27 | 22 |
|
28 | 23 | private static final Logger LOGGER = LoggerFactory.getLogger(AutosaveManager.class);
|
| 24 | + private static final int AUTO_SAVE_DELAY = 200; |
29 | 25 |
|
30 | 26 | private static Set<AutosaveManager> runningInstances = new HashSet<>();
|
31 | 27 |
|
32 | 28 | private final BibDatabaseContext bibDatabaseContext;
|
33 |
| - private final BlockingQueue<Runnable> workerQueue; |
34 |
| - private final ExecutorService executor; |
| 29 | + private final ScheduledExecutorService executor; |
35 | 30 | private final EventBus eventBus;
|
36 | 31 | private final CoarseChangeFilter changeFilter;
|
| 32 | + private Future<?> scheduledSaveAction; |
37 | 33 |
|
38 | 34 | private AutosaveManager(BibDatabaseContext bibDatabaseContext) {
|
39 | 35 | this.bibDatabaseContext = bibDatabaseContext;
|
40 |
| - this.workerQueue = new ArrayBlockingQueue<>(1); |
41 |
| - this.executor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, workerQueue); |
| 36 | + ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1); |
| 37 | + executor.setRemoveOnCancelPolicy(true); // This prevents memory leaks |
| 38 | + this.executor = executor; |
42 | 39 | this.eventBus = new EventBus();
|
43 | 40 | this.changeFilter = new CoarseChangeFilter(bibDatabaseContext);
|
44 | 41 | changeFilter.registerListener(this);
|
45 | 42 | }
|
46 | 43 |
|
47 | 44 | @Subscribe
|
48 | 45 | public synchronized void listen(@SuppressWarnings("unused") BibDatabaseContextChangedEvent event) {
|
49 |
| - try { |
50 |
| - executor.submit(() -> { |
51 |
| - eventBus.post(new AutosaveEvent()); |
52 |
| - }); |
53 |
| - } catch (RejectedExecutionException e) { |
54 |
| - LOGGER.debug("Rejecting autosave while another save process is already running."); |
| 46 | + if(scheduledSaveAction != null) { |
| 47 | + scheduledSaveAction.cancel(false); |
55 | 48 | }
|
| 49 | + scheduledSaveAction = executor.schedule(() -> { |
| 50 | + eventBus.post(new AutosaveEvent()); |
| 51 | + }, AUTO_SAVE_DELAY, TimeUnit.MILLISECONDS); |
56 | 52 | }
|
57 | 53 |
|
58 | 54 | private void shutdown() {
|
|
0 commit comments