1 package org.xvsm.core;
2
3 import java.net.URI;
4 import java.util.Map;
5 import java.util.HashMap;
6 import java.util.concurrent.ConcurrentHashMap;
7 import java.util.concurrent.locks.ReadWriteLock;
8 import java.util.concurrent.locks.ReentrantReadWriteLock;
9
10 public class VirtualAnswerContainer {
11
12 private static Map<URI, VirtualAnswerContainer> instances = new ConcurrentHashMap<URI, VirtualAnswerContainer>();
13
14 private Entry[] result = null;
15
16 private URI containerURI = null;
17
18 /***
19 * Get the instance of a specific container.
20 *
21 * @containerURI the uri of the container
22 * @return
23 *
24 */
25 public static VirtualAnswerContainer getOrCreateInstance(URI containerURI) {
26 if (!instances.containsKey(containerURI)) {
27 instances.put(containerURI,
28 new VirtualAnswerContainer(containerURI));
29 }
30 return instances.get(containerURI);
31 }
32
33 public static VirtualAnswerContainer getInstance(URI containerURI) {
34 return instances.get(containerURI);
35 }
36
37 /***
38 * Default Constructor.
39 */
40 private VirtualAnswerContainer(URI uri) {
41 this.containerURI = uri;
42 }
43
44 /***
45 *
46 * @param answerToContainer
47 * @return
48 * @throws InterruptedException
49 */
50 public Entry[] wait(URI answerToContainer) throws InterruptedException {
51 if (this.result != null) {
52 return this.returnEntries();
53 } else {
54 synchronized (this) {
55 this.wait();
56 }
57 }
58 return this.returnEntries();
59 }
60
61 /***
62 * Return this.results and sets it to null afterwards.
63 *
64 * @return
65 */
66 private Entry[] returnEntries() {
67 Entry[] e = this.result;
68 this.result = null;
69 return e;
70 }
71
72 /***
73 *
74 * @param answer
75 * @param answerToContainer
76 */
77 public void writeAnswer(Entry[] answer, URI answerToContainer) {
78 this.result = answer;
79 synchronized (this) {
80 this.notify();
81 }
82 }
83
84 public URI getContainerURI() {
85 return containerURI;
86 }
87 }