PageRenderTime 35ms CodeModel.GetById 26ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/hazelcast-hibernate/src/main/java/com/hazelcast/hibernate/local/CleanupService.java

https://bitbucket.org/gabral6_gmailcom/hazelcast
Java | 74 lines | 43 code | 13 blank | 18 comment | 0 complexity | 324b2e4cc58dcf7a72b41564835722e2 MD5 | raw file
 1/*
 2 * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
 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
17package com.hazelcast.hibernate.local;
18
19import com.hazelcast.impl.OutOfMemoryErrorDispatcher;
20
21import java.util.concurrent.Executors;
22import java.util.concurrent.ScheduledExecutorService;
23import java.util.concurrent.ThreadFactory;
24import java.util.concurrent.TimeUnit;
25
26/**
27 * @mdogan 11/14/12
28 */
29public final class CleanupService {
30
31    private final String name;
32    private final ScheduledExecutorService executor;
33
34    public CleanupService(final String name) {
35        this.name = name;
36        executor = Executors.newSingleThreadScheduledExecutor(new CleanupThreadFactory());
37    }
38
39    public void registerCache(final LocalRegionCache cache) {
40        executor.scheduleWithFixedDelay(new Runnable() {
41            public void run() {
42                cache.cleanup();
43            }
44        }, 60, 60, TimeUnit.SECONDS);
45    }
46
47    public void stop() {
48        executor.shutdownNow();
49    }
50
51    private class CleanupThreadFactory implements ThreadFactory {
52
53        public Thread newThread(final Runnable r) {
54            final Thread thread = new CleanupThread(r, name + ".hibernate.cleanup");
55            thread.setDaemon(true);
56            return thread;
57        }
58    }
59
60    private class CleanupThread extends Thread {
61
62        private CleanupThread(final Runnable target, final String name) {
63            super(target, name);
64        }
65
66        public void run() {
67            try {
68                super.run();
69            } catch (OutOfMemoryError e) {
70                OutOfMemoryErrorDispatcher.onOutOfMemory(e);
71            }
72        }
73    }
74}