PageRenderTime 60ms CodeModel.GetById 12ms app.highlight 41ms RepoModel.GetById 2ms app.codeStats 0ms

/hazelcast/src/main/java/com/hazelcast/impl/ThreadContext.java

https://bitbucket.org/gabral6_gmailcom/hazelcast
Java | 257 lines | 191 code | 46 blank | 20 comment | 24 complexity | 8252dfec3a9e6b1d72068c1f4c5b0911 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
 17package com.hazelcast.impl;
 18
 19import com.hazelcast.core.ManagedContext;
 20import com.hazelcast.impl.ConcurrentMapManager.MEvict;
 21import com.hazelcast.logging.ILogger;
 22import com.hazelcast.logging.Logger;
 23import com.hazelcast.nio.Data;
 24import com.hazelcast.nio.Serializer;
 25
 26import java.util.HashMap;
 27import java.util.Iterator;
 28import java.util.Map;
 29import java.util.concurrent.ConcurrentHashMap;
 30import java.util.concurrent.ConcurrentMap;
 31import java.util.concurrent.atomic.AtomicInteger;
 32import java.util.logging.Level;
 33
 34public final class ThreadContext {
 35
 36    private final static AtomicInteger newThreadId = new AtomicInteger();
 37
 38    private static final ConcurrentMap<Thread, ThreadContext> mapContexts = new ConcurrentHashMap<Thread, ThreadContext>(1000);
 39
 40    private final Thread thread;
 41
 42    private final Serializer serializer = new Serializer();
 43
 44    private final Map<FactoryImpl, HazelcastInstanceThreadContext> mapHazelcastInstanceContexts = new HashMap<FactoryImpl, HazelcastInstanceThreadContext>(2);
 45
 46    private volatile FactoryImpl currentFactory = null;
 47
 48    private ThreadContext(Thread thread) {
 49        this.thread = thread;
 50    }
 51
 52    public static ThreadContext get() {
 53        Thread currentThread = Thread.currentThread();
 54        ThreadContext threadContext = mapContexts.get(currentThread);
 55        if (threadContext == null) {
 56            try {
 57                threadContext = new ThreadContext(Thread.currentThread());
 58                mapContexts.put(currentThread, threadContext);
 59                Iterator<Thread> threads = mapContexts.keySet().iterator();
 60                while (threads.hasNext()) {
 61                    Thread thread = threads.next();
 62                    if (!thread.isAlive()) {
 63                        threads.remove();
 64                    }
 65                }
 66            } catch (OutOfMemoryError e) {
 67                OutOfMemoryErrorDispatcher.onOutOfMemory(e);
 68                throw e;
 69            }
 70            if (mapContexts.size() > 1000) {
 71                String msg = " ThreadContext is created!! You might have too many threads. Is that normal?";
 72                Logger.getLogger(ThreadContext.class.getName()).log(Level.WARNING, mapContexts.size() + msg);
 73            }
 74        }
 75        return threadContext;
 76    }
 77
 78    public static void shutdownAll() {
 79        mapContexts.clear();
 80    }
 81
 82    public static synchronized void shutdown(Thread thread) {
 83        ThreadContext threadContext = mapContexts.remove(thread);
 84        if (threadContext != null) {
 85            threadContext.shutdown();
 86        }
 87    }
 88
 89    public void shutdown() {
 90        currentFactory = null;
 91        mapHazelcastInstanceContexts.clear();
 92    }
 93
 94    public void shutdown(FactoryImpl factory) {
 95        mapHazelcastInstanceContexts.remove(factory);
 96    }
 97
 98    public void finalizeTxn() {
 99        getCallContext().finalizeTransaction();
100    }
101
102    public TransactionImpl getTransaction() {
103        return getCallContext().getTransaction();
104    }
105
106    public long getTxnId() {
107        return getCallContext().getTxnId();
108    }
109
110    public FactoryImpl getCurrentFactory() {
111        return currentFactory;
112    }
113
114    public ManagedContext getCurrentManagedContext() {
115        return currentFactory != null ? currentFactory.managedContext : null;
116    }
117
118    public void setCurrentFactory(FactoryImpl currentFactory) {
119        this.currentFactory = currentFactory;
120    }
121
122    public void reset() {
123        finalizeTxn();
124    }
125
126    public byte[] toByteArray(Object obj) {
127        return serializer.toByteArray(obj);
128    }
129
130    public Data toData(Object obj) {
131        return serializer.writeObject(obj);
132    }
133
134    public Object toObject(Data data) {
135        return serializer.readObject(data);
136    }
137
138    public HazelcastInstanceThreadContext getHazelcastInstanceThreadContext(FactoryImpl factory) {
139        if (factory == null) {
140            ILogger logger = Logger.getLogger(ThreadContext.class.getName());
141            logger.log(Level.SEVERE, "Factory is null", new Throwable());
142        }
143        HazelcastInstanceThreadContext hic = mapHazelcastInstanceContexts.get(factory);
144        if (hic != null) return hic;
145        hic = new HazelcastInstanceThreadContext(factory);
146        mapHazelcastInstanceContexts.put(factory, hic);
147        return hic;
148    }
149
150    public CallCache getCallCache(FactoryImpl factory) {
151        return getHazelcastInstanceThreadContext(factory).getCallCache();
152    }
153
154    /**
155     * Is this thread remote Java or CSharp Client thread?
156     *
157     * @return true if the thread is for Java or CSharp Client, false otherwise
158     */
159    public boolean isClient() {
160        return getCallContext().isClient();
161    }
162
163    public int createNewThreadId() {
164        return newThreadId.incrementAndGet();
165    }
166
167    public CallContext getCallContext() {
168        return getHazelcastInstanceThreadContext(currentFactory).getCallContext();
169    }
170
171    class HazelcastInstanceThreadContext {
172        FactoryImpl factory;
173        CallCache callCache;
174        volatile CallContext callContext = null;
175
176        HazelcastInstanceThreadContext(FactoryImpl factory) {
177            this.factory = factory;
178            callContext = (new CallContext(createNewThreadId(), false));
179        }
180
181        public CallCache getCallCache() {
182            if (callCache == null) {
183                callCache = new CallCache(factory);
184            }
185            return callCache;
186        }
187
188        public CallContext getCallContext() {
189            return callContext;
190        }
191
192        public void setCallContext(CallContext callContext) {
193            this.callContext = callContext;
194        }
195    }
196
197    class CallCache {
198        final FactoryImpl factory;
199        final ConcurrentMapManager.MPut mput;
200        final ConcurrentMapManager.MGet mget;
201        final ConcurrentMapManager.MRemove mremove;
202        final ConcurrentMapManager.MEvict mevict;
203
204        CallCache(FactoryImpl factory) {
205            this.factory = factory;
206            mput = factory.node.concurrentMapManager.new MPut();
207            mget = factory.node.concurrentMapManager.new MGet();
208            mremove = factory.node.concurrentMapManager.new MRemove();
209            mevict = factory.node.concurrentMapManager.new MEvict();
210        }
211
212        public ConcurrentMapManager.MPut getMPut() {
213            mput.reset();
214            mput.request.lastTime = System.nanoTime();
215            return mput;
216        }
217
218        public ConcurrentMapManager.MGet getMGet() {
219            mget.reset();
220            mget.request.lastTime = System.nanoTime();
221            return mget;
222        }
223
224        public ConcurrentMapManager.MRemove getMRemove() {
225            mremove.reset();
226            mremove.request.lastTime = System.nanoTime();
227            return mremove;
228        }
229
230        public MEvict getMEvict() {
231            mevict.reset();
232            return mevict;
233        }
234    }
235
236    public int getThreadId() {
237        return getCallContext().getThreadId();
238    }
239
240    public void setCallContext(CallContext callContext) {
241        getHazelcastInstanceThreadContext(currentFactory).setCallContext(callContext);
242    }
243
244    @Override
245    public boolean equals(Object o) {
246        if (this == o) return true;
247        if (o == null || getClass() != o.getClass()) return false;
248        ThreadContext that = (ThreadContext) o;
249        if (thread != null ? !thread.equals(that.thread) : that.thread != null) return false;
250        return true;
251    }
252
253    @Override
254    public int hashCode() {
255        return thread != null ? thread.hashCode() : 0;
256    }
257}