/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. package com.hazelcast.hibernate.local;
  17. import com.hazelcast.impl.OutOfMemoryErrorDispatcher;
  18. import java.util.concurrent.Executors;
  19. import java.util.concurrent.ScheduledExecutorService;
  20. import java.util.concurrent.ThreadFactory;
  21. import java.util.concurrent.TimeUnit;
  22. /**
  23. * @mdogan 11/14/12
  24. */
  25. public final class CleanupService {
  26. private final String name;
  27. private final ScheduledExecutorService executor;
  28. public CleanupService(final String name) {
  29. this.name = name;
  30. executor = Executors.newSingleThreadScheduledExecutor(new CleanupThreadFactory());
  31. }
  32. public void registerCache(final LocalRegionCache cache) {
  33. executor.scheduleWithFixedDelay(new Runnable() {
  34. public void run() {
  35. cache.cleanup();
  36. }
  37. }, 60, 60, TimeUnit.SECONDS);
  38. }
  39. public void stop() {
  40. executor.shutdownNow();
  41. }
  42. private class CleanupThreadFactory implements ThreadFactory {
  43. public Thread newThread(final Runnable r) {
  44. final Thread thread = new CleanupThread(r, name + ".hibernate.cleanup");
  45. thread.setDaemon(true);
  46. return thread;
  47. }
  48. }
  49. private class CleanupThread extends Thread {
  50. private CleanupThread(final Runnable target, final String name) {
  51. super(target, name);
  52. }
  53. public void run() {
  54. try {
  55. super.run();
  56. } catch (OutOfMemoryError e) {
  57. OutOfMemoryErrorDispatcher.onOutOfMemory(e);
  58. }
  59. }
  60. }
  61. }