01: /**
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */package org.apache.openejb.core.ivm;
17:
18: import java.io.Externalizable;
19: import java.io.IOException;
20: import java.io.InvalidObjectException;
21: import java.io.ObjectInput;
22: import java.io.ObjectOutput;
23: import java.io.ObjectStreamException;
24: import java.util.ArrayList;
25: import java.util.List;
26:
27: public class IntraVmArtifact implements Externalizable {
28: private static final List<Object> staticHandles = new ArrayList<Object>();
29:
30: private static final ThreadLocal<List<Object>> threadHandles = new ThreadLocal<List<Object>>() {
31: protected List<Object> initialValue() {
32: return new ArrayList<Object>();
33: }
34: };
35:
36: // todo why not put in message catalog?
37: private static final String NO_ARTIFACT_ERROR = "The artifact this object represents could not be found.";
38:
39: private int instanceHandle;
40: private boolean staticArtifact;
41:
42: public IntraVmArtifact(Object obj) {
43: this (obj, false);
44: }
45:
46: public IntraVmArtifact(Object obj, boolean storeStatically) {
47: this .staticArtifact = storeStatically;
48: List<Object> list = getHandles(storeStatically);
49: instanceHandle = list.size();
50: list.add(obj);
51: }
52:
53: private static List<Object> getHandles(boolean staticArtifact) {
54: return (staticArtifact) ? staticHandles : threadHandles.get();
55: }
56:
57: public IntraVmArtifact() {
58: }
59:
60: public void writeExternal(ObjectOutput out) throws IOException {
61: out.write(instanceHandle);
62: }
63:
64: public void readExternal(ObjectInput in) throws IOException {
65: instanceHandle = in.read();
66: }
67:
68: protected Object readResolve() throws ObjectStreamException {
69: List<Object> list = getHandles(staticArtifact);
70: Object artifact = list.get(instanceHandle);
71: if (artifact == null)
72: throw new InvalidObjectException(NO_ARTIFACT_ERROR
73: + instanceHandle);
74: // todo WHY?
75: if (list.size() == instanceHandle + 1) {
76: list.clear();
77: }
78: return artifact;
79: }
80:
81: }
|