1 2 3 package com.db4odoc.f1.semaphores; 4 5 import com.db4o.*; 6 import com.db4o.query.*; 7 8 14 public class Singleton { 15 16 20 public static Object getSingleton(ObjectContainer objectContainer, Class clazz) { 21 22 Object obj = queryForSingletonClass(objectContainer, clazz); 23 if (obj != null) { 24 return obj; 25 } 26 27 String semaphore = "Singleton#getSingleton_" + clazz.getName(); 28 29 if (!objectContainer.ext().setSemaphore(semaphore, 10000)) { 30 throw new RuntimeException ("Blocked semaphore " + semaphore); 31 } 32 33 obj = queryForSingletonClass(objectContainer, clazz); 34 35 if (obj == null) { 36 37 try { 38 obj = clazz.newInstance(); 39 } catch (InstantiationException e) { 40 e.printStackTrace(); 41 } catch (IllegalAccessException e) { 42 e.printStackTrace(); 43 } 44 45 objectContainer.set(obj); 46 47 53 objectContainer.commit(); 54 55 } 56 57 objectContainer.ext().releaseSemaphore(semaphore); 58 59 return obj; 60 } 61 62 private static Object queryForSingletonClass(ObjectContainer objectContainer, Class clazz) { 63 Query q = objectContainer.query(); 64 q.constrain(clazz); 65 ObjectSet objectSet = q.execute(); 66 if (objectSet.size() == 1) { 67 return objectSet.next(); 68 } 69 if (objectSet.size() > 1) { 70 throw new RuntimeException ( 71 "Singleton problem. Multiple instances of: " + clazz.getName()); 72 } 73 return null; 74 } 75 76 } 77 | Popular Tags |