1 /***
2 * Copyright 2003-2010 Terracotta, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package net.sf.ehcache.writer.writebehind;
17
18 import net.sf.ehcache.Cache;
19 import net.sf.ehcache.CacheEntry;
20 import net.sf.ehcache.CacheException;
21 import net.sf.ehcache.Element;
22 import net.sf.ehcache.writer.CacheWriter;
23 import net.sf.ehcache.writer.CacheWriterManager;
24
25 /***
26 * Implements a {@code WriterManager} that writes elements to a queue first and in the background sends the to the {@code CacheWriter}.
27 *
28 * @author Geert Bevin
29 * @version $Id: WriteBehindManager.html 13146 2011-08-01 17:12:39Z oletizi $
30 */
31 public class WriteBehindManager implements CacheWriterManager {
32 private volatile WriteBehind writeBehind;
33
34 /***
35 * {@inheritDoc}
36 */
37 public void init(Cache cache) throws CacheException {
38 if (cache.isTerracottaClustered()) {
39 writeBehind = cache.getCacheManager().createTerracottaWriteBehind(cache);
40 } else {
41 writeBehind = new WriteBehindQueueManager(cache.getCacheConfiguration());
42 }
43
44 CacheWriter cacheWriter = cache.getRegisteredCacheWriter();
45 if (null == cacheWriter) {
46 throw new CacheException("No cache writer was registered for cache " + cache.getName());
47 }
48
49 if (cache.getCacheConfiguration().getCacheWriterConfiguration().getWriteCoalescing()) {
50 writeBehind.setOperationsFilter(new CoalesceKeysFilter());
51 }
52
53 writeBehind.start(cacheWriter);
54 }
55
56 /***
57 * {@inheritDoc}
58 */
59 public void put(Element element) throws CacheException {
60 writeBehind.write(element);
61 }
62
63 /***
64 * {@inheritDoc}
65 */
66 public void remove(CacheEntry entry) throws CacheException {
67 writeBehind.delete(entry);
68 }
69
70 /***
71 * {@inheritDoc}
72 */
73 public void dispose() {
74
75 if (writeBehind != null) {
76 writeBehind.stop();
77 }
78 }
79
80 /***
81 * Gets the best estimate for items in the queue still awaiting processing.
82 * Not including elements currently processed
83 * @return the amount of elements still awaiting processing.
84 */
85 public long getQueueSize() {
86 return writeBehind.getQueueSize();
87 }
88 }