File D:\maven-qcr-plugin-testsunitaires\qcr4java\h2-1.3.170-sources\target\site\qc\lecode\util\SynchronizedVerifier.java.html

1 /*
2 * Copyright 2004-2011 H2 Group. Multiple-Licensed under the H2 License,
3 * Version 1.0, and under the Eclipse Public License, Version 1.0
4 * (http://h2database.com/html/license.html).
5 * Initial Developer: H2 Group
6 */
7 package org.h2.util;
8
9 import java.util.Collections;
10 import java.util.HashMap;
11 import java.util.IdentityHashMap;
12 import java.util.Map;
13 import java.util.concurrent.atomic.AtomicBoolean;
14
15 /**
16 * A utility class that allows to verify access to a resource is synchronized.
17 */
18 public class SynchronizedVerifier {
19
20 private static volatile boolean enabled;
21 private static final Map<Class<?>, AtomicBoolean> DETECT =
22 Collections.synchronizedMap(new HashMap<Class<?>, AtomicBoolean>());
23 private static final Map<Object, Object> CURRENT =
24 Collections.synchronizedMap(new IdentityHashMap<Object, Object>());
25
26 /**
27 * Enable or disable detection for a given class.
28 *
29 * @param clazz the class
30 * @param value the new value (true means detection is enabled)
31 */
32 public static void setDetect(Class<?> clazz, boolean value) {
33 if (value) {
34 DETECT.put(clazz, new AtomicBoolean());
35 } else {
36 AtomicBoolean b = DETECT.remove(clazz);
37 if (b == null) {
38 throw new AssertionError("Detection was not enabled");
39 } else if (!b.get()) {
40 throw new AssertionError("No object of this class was tested");
41 }
42 }
43 enabled = DETECT.size() > 0;
44 }
45
46 /**
47 * Verify the object is not accessed concurrently.
48 *
49 * @param o the object
50 */
51 public static void check(Object o) {
52 if (enabled) {
53 detectConcurrentAccess(o);
54 }
55 }
56
57 private static void detectConcurrentAccess(Object o) {
58 AtomicBoolean value = DETECT.get(o.getClass());
59 if (value != null) {
60 value.set(true);
61 if (CURRENT.remove(o) != null) {
62 throw new AssertionError("Concurrent access");
63 }
64 CURRENT.put(o, o);
65 try {
66 Thread.sleep(1);
67 } catch (InterruptedException e) {
68 // ignore
69 }
70 Object old = CURRENT.remove(o);
71 if (old == null) {
72 throw new AssertionError("Concurrent access");
73 }
74 }
75 }
76
77 }
78