| 1 | package org.jtoolkit.essence.data.impl; |
| 2 | /* |
| 3 | Copyright 2006 Peter Lawrey |
| 4 | |
| 5 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | you may not use this file except in compliance with the License. |
| 7 | You may obtain a copy of the License at |
| 8 | |
| 9 | http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | |
| 11 | Unless required by applicable law or agreed to in writing, software |
| 12 | distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | See the License for the specific language governing permissions and |
| 15 | limitations under the License. |
| 16 | */ |
| 17 | |
| 18 | import org.jetbrains.annotations.NotNull; |
| 19 | |
| 20 | import java.lang.ref.Reference; |
| 21 | import java.lang.ref.WeakReference; |
| 22 | import java.util.Set; |
| 23 | |
| 24 | /** |
| 25 | * A class which can be periodically flushed. |
| 26 | */ |
| 27 | interface Flushable { |
| 28 | public static class Flusher implements Runnable { |
| 29 | private final Reference<Set<String>> dirtyRef; |
| 30 | private final Reference<Flushable> flushableRef; |
| 31 | |
| 32 | public Flusher(@NotNull Set<String> dirty, @NotNull Flushable flushable) { |
| 33 | dirtyRef = new WeakReference<Set<String>>(dirty); |
| 34 | flushableRef = new WeakReference<Flushable>(flushable); |
| 35 | } |
| 36 | |
| 37 | public void run() { |
| 38 | Set<String> dirty = dirtyRef.get(); |
| 39 | Flushable flushable = flushableRef.get(); |
| 40 | if (dirty == null || flushable == null) |
| 41 | throw new IllegalStateException(); |
| 42 | |
| 43 | String[] dirtyFilenames; |
| 44 | synchronized (dirty) { |
| 45 | if (dirty.isEmpty()) return; |
| 46 | dirtyFilenames = dirty.toArray(new String[dirty.size()]); |
| 47 | dirty.clear(); |
| 48 | } |
| 49 | for (String dirtyFilename : dirtyFilenames) |
| 50 | if (!flushable.flush(dirtyFilename)) { |
| 51 | synchronized (dirty) { |
| 52 | dirty.add(dirtyFilename); |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | public boolean flush(String filename); |
| 60 | } |