Example usage for java.lang ThreadLocal ThreadLocal

List of usage examples for java.lang ThreadLocal ThreadLocal

Introduction

In this page you can find the example usage for java.lang ThreadLocal ThreadLocal.

Prototype

public ThreadLocal() 

Source Link

Document

Creates a thread local variable.

Usage

From source file:com.foursquare.twofishes.io.MapFileConcurrentReader.java

protected synchronized void open(Path dir, WritableComparator comparator, final Configuration conf,
        final SequenceFile.Reader.Option... options) throws IOException {
    final Path dataFile = new Path(dir, MapFile.DATA_FILE_NAME);
    final Path indexFile = new Path(dir, MapFile.INDEX_FILE_NAME);

    // open the data
    this.data = new ThreadLocal<SequenceFile.Reader>() {
        protected SequenceFile.Reader initialValue() {
            try {
                SequenceFile.Reader r = createDataFileReader(dataFile, conf, options);
                LOG.info("opened new SequenceFile.Reader for " + dataFile);
                synchronized (this) {
                    allDataFiles.add(r);
                }/*from w ww .  j a v  a  2s .  co  m*/
                return r;
            } catch (IOException ioe) {
                throw new RuntimeException(ioe);
            }
        }
    };
    this.firstPosition = data.get().getPosition();

    this.comparator = WritableComparator.get(data.get().getKeyClass().asSubclass(WritableComparable.class));

    // open the index
    SequenceFile.Reader.Option[] indexOptions = Options.prependOptions(options,
            SequenceFile.Reader.file(indexFile));
    this.index = new SequenceFile.Reader(conf, indexOptions);
}

From source file:net.netheos.pcsapi.oauth.PasswordSessionManager.java

private synchronized HttpContext getHttpContext(HttpHost host) {
    ThreadLocal<HttpContext> tlContext = cache.get(host);
    if (tlContext == null) {
        tlContext = new ThreadLocal<HttpContext>();
        cache.put(host, tlContext);/*from w w  w  .j  a v  a 2  s.com*/
    }
    HttpContext context = tlContext.get();
    if (context == null) {
        AuthScope scope = new AuthScope(host.getHostName(), host.getPort());
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(scope, usernamePasswordCredentials);

        context = new BasicHttpContext();
        context.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider);
        tlContext.set(context);
    }
    return context;
}

From source file:org.apache.hadoop.io.MapFileConcurrentReader.java

protected synchronized void open(Path dir, WritableComparator comparator, final Configuration conf,
        final SequenceFile.Reader.Option... options) throws IOException {
    final Path dataFile = new Path(dir, MapFile.DATA_FILE_NAME);
    final Path indexFile = new Path(dir, MapFile.INDEX_FILE_NAME);

    // open the data
    this.data = new ThreadLocal<SequenceFile.Reader>() {
        protected SequenceFile.Reader initialValue() {
            try {
                SequenceFile.Reader r = createDataFileReader(dataFile, conf, options);
                LOG.info("opened new SequenceFile.Reader for " + dataFile);
                synchronized (this) {
                    allDataFiles.add(r);
                }/*from   ww  w  .  ja  v a2 s.  c o  m*/
                return r;
            } catch (IOException ioe) {
                throw new RuntimeException(ioe);
            }
        }
    };
    this.firstPosition = data.get().getPosition();

    if (comparator == null)
        this.comparator = WritableComparator.get(data.get().getKeyClass().asSubclass(WritableComparable.class));
    else
        this.comparator = comparator;

    // open the index
    SequenceFile.Reader.Option[] indexOptions = Options.prependOptions(options,
            SequenceFile.Reader.file(indexFile));
    this.index = new SequenceFile.Reader(conf, indexOptions);
}

From source file:fr.ippon.wip.http.hc.HttpClientResourceManager.java

private HttpClientResourceManager() {
    perUserClientMap = Collections.synchronizedMap(new HashMap<String, HttpClient>());
    perUserCookieStoreMap = Collections.synchronizedMap(new HashMap<String, CookieStore>());
    perUserWindowCredentialProviderMap = Collections
            .synchronizedMap(new HashMap<String, CredentialsProvider>());
    currentPortletRequest = new ThreadLocal<PortletRequest>();
    currentPortletResponse = new ThreadLocal<PortletResponse>();
    currentRequest = new ThreadLocal<RequestBuilder>();

    try {/*from w w  w . jav  a 2 s  . c  o  m*/
        SSLSocketFactory ssf = new SSLSocketFactory(new TrustSelfSignedStrategy(),
                new AllowAllHostnameVerifier());
        Scheme httpsScheme = new Scheme("https", 443, ssf);
        PlainSocketFactory psf = new PlainSocketFactory();
        Scheme httpScheme = new Scheme("http", 80, psf);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(httpsScheme);
        registry.register(httpScheme);
        connectionManager = new PoolingClientConnectionManager(registry);
        connectionManager.setDefaultMaxPerRoute(10);
        connectionManager.setMaxTotal(100);

        DefaultHttpClient defaultHttpClient = new DefaultHttpClient(connectionManager);

        // automatically redirects all HEAD, GET and POST requests
        defaultHttpClient.setRedirectStrategy(new LaxRedirectStrategy());

        CacheConfig cacheConfig = createAndConfigureCache();

        URL ehCacheConfig = getClass().getResource("/ehcache.xml");
        cacheManager = CacheManager.create(ehCacheConfig);
        Ehcache ehcache = cacheManager.getEhcache("public");
        EhcacheHttpCacheStorage httpCacheStorage = new EhcacheHttpCacheStorage(ehcache);

        CachingHttpClient sharedCacheClient = new CachingHttpClient(defaultHttpClient, httpCacheStorage,
                cacheConfig);
        HttpClientDecorator decoratedClient = new HttpClientDecorator(sharedCacheClient);

        decoratedClient.addPreProcessor(new LtpaRequestInterceptor());
        decoratedClient.addPreProcessor(new StaleIfErrorRequestInterceptor(staleIfErrorTime));
        decoratedClient.addFilter(new IgnoreHttpRequestFilter());

        decoratedClient.addPostProcessor(new TransformerResponseInterceptor());

        rootClient = decoratedClient;

    } catch (Exception e) {
        throw new RuntimeException("Could not initialize connection manager", e);
    }

}

From source file:org.apache.lens.cube.metadata.UpdatePeriod.java

private static DateFormat getMonthlyFormat() {
    if (monthlyFormat == null) {
        monthlyFormat = new ThreadLocal<DateFormat>() {
            @Override//from  w ww  .jav  a  2  s .co  m
            protected SimpleDateFormat initialValue() {
                return new SimpleDateFormat(MONTHLY.formatStr());
            }
        };
    }
    return monthlyFormat.get();
}

From source file:org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigGenericMapReduce.java

public static void staticDataCleanup() {
    sJobContext = null;
    sJobConf = null;
    sJobConfInternal = new ThreadLocal<Configuration>();
}

From source file:com.espertech.esper.core.EPRuntimeIsolatedImpl.java

/**
 * Ctor./*from  w  w  w.j a  v a 2 s. c o  m*/
 * @param svc isolated services
 * @param unisolatedSvc engine services
 */
public EPRuntimeIsolatedImpl(EPIsolationUnitServices svc, EPServicesContext unisolatedSvc) {
    this.services = svc;
    this.unisolatedServices = unisolatedSvc;
    this.threadWorkQueue = new ThreadWorkQueue();
    isSubselectPreeval = unisolatedSvc.getEngineSettingsService().getEngineSettings().getExpression()
            .isSelfSubselectPreeval();
    isPrioritized = unisolatedSvc.getEngineSettingsService().getEngineSettings().getExecution().isPrioritized();
    isLatchStatementInsertStream = unisolatedSvc.getEngineSettingsService().getEngineSettings().getThreading()
            .isInsertIntoDispatchPreserveOrder();

    isolatedTimeEvalContext = new ExprEvaluatorContext() {
        private ExpressionResultCacheService expressionResultCacheService = new ExpressionResultCacheService();

        public TimeProvider getTimeProvider() {
            return services.getSchedulingService();
        }

        public ExpressionResultCacheService getExpressionResultCacheService() {
            return expressionResultCacheService;
        }
    };

    matchesPerStmtThreadLocal = new ThreadLocal<Map<EPStatementHandle, ArrayDeque<FilterHandleCallback>>>() {
        protected synchronized Map<EPStatementHandle, ArrayDeque<FilterHandleCallback>> initialValue() {
            if (isPrioritized) {
                return new TreeMap<EPStatementHandle, ArrayDeque<FilterHandleCallback>>(
                        new Comparator<EPStatementHandle>() {
                            public int compare(EPStatementHandle o1, EPStatementHandle o2) {
                                if (o1 == o2) {
                                    return 0;
                                }
                                if (o1.equals(o2)) {
                                    return 0;
                                }
                                return o1.getPriority() >= o2.getPriority() ? -1 : 1;
                            }
                        });
            } else {
                return new HashMap<EPStatementHandle, ArrayDeque<FilterHandleCallback>>(10000);
            }
        }
    };

    schedulePerStmtThreadLocal = new ThreadLocal<Map<EPStatementHandle, Object>>() {
        protected synchronized Map<EPStatementHandle, Object> initialValue() {
            if (isPrioritized) {
                return new TreeMap<EPStatementHandle, Object>(new Comparator<EPStatementHandle>() {
                    public int compare(EPStatementHandle o1, EPStatementHandle o2) {
                        if (o1 == o2) {
                            return 0;
                        }
                        if (o1.equals(o2)) {
                            return 0;
                        }
                        return o1.getPriority() >= o2.getPriority() ? -1 : 1;
                    }
                });
            } else {
                return new HashMap<EPStatementHandle, Object>(10000);
            }
        }
    };
}

From source file:org.apache.hive.service.cli.thrift.ThriftCLIService_bak.java

public ThriftCLIService_bak(CLIService service, String serviceName) {
    super(serviceName);
    this.cliService = service;
    currentServerContext = new ThreadLocal<ServerContext>();
    serverEventHandler = new TServerEventHandler() {
        @Override/*from ww  w. j av  a 2  s .  c  om*/
        public ServerContext createContext(TProtocol input, TProtocol output) {
            Metrics metrics = MetricsFactory.getInstance();
            if (metrics != null) {
                try {
                    metrics.incrementCounter(MetricsConstant.OPEN_CONNECTIONS);
                } catch (Exception e) {
                    LOG.warn("Error Reporting JDO operation to Metrics system", e);
                }
            }
            return new ThriftCLIServerContext();
        }

        @Override
        public void deleteContext(ServerContext serverContext, TProtocol input, TProtocol output) {
            Metrics metrics = MetricsFactory.getInstance();
            if (metrics != null) {
                try {
                    metrics.decrementCounter(MetricsConstant.OPEN_CONNECTIONS);
                } catch (Exception e) {
                    LOG.warn("Error Reporting JDO operation to Metrics system", e);
                }
            }
            ThriftCLIServerContext context = (ThriftCLIServerContext) serverContext;
            SessionHandle sessionHandle = context.getSessionHandle();
            if (sessionHandle != null) {
                LOG.info("Session disconnected without closing properly, close it now");
                try {
                    cliService.closeSession(sessionHandle);
                } catch (HiveSQLException e) {
                    LOG.warn("Failed to close session: " + e, e);
                }
            }
        }

        @Override
        public void preServe() {
        }

        @Override
        public void processContext(ServerContext serverContext, TTransport input, TTransport output) {
            currentServerContext.set(serverContext);
        }
    };
}

From source file:org.apache.sandesha2.storage.jdbc.PersistentStorageManager.java

public PersistentStorageManager(ConfigurationContext context) throws SandeshaException {
    super(context);
    log.info("create PersistentStorageManager");
    storageMap = new HashMap<String, MessageContext>();
    threadTransaction = new ThreadLocal<Transaction>();
    pRMSBeanMgr = new PersistentRMSBeanMgr(this);
    pRMDBeanMgr = new PersistentRMDBeanMgr(this);
    pSenderBeanMgr = new PersistentSenderBeanMgr(this);
    pInvokerBeanMgr = new PersistentInvokerBeanMgr(this);
    sender = new Sender();
    // Note that while inOrder is a global property we can decide if we need the
    // invoker thread at this point. If we change this to be a sequence-level
    // property then we'll need to revisit this.
    SandeshaPolicyBean policy = SandeshaUtil.getPropertyBean(context.getAxisConfiguration());
    useSerialization = policy.isUseMessageSerialization();
    if (policy.isInOrder())
        invoker = new Invoker();
    if (policy.isEnableMakeConnection())
        pollingManager = new PollingManager();
    ModuleConfiguration mc = context.getAxisConfiguration().getModuleConfig("sandesha2");
    if (mc != null) {
        Parameter param = mc.getParameter("db.connectionstring");
        if (param != null) {
            dbConnectionString = (String) param.getValue();
            log.debug(param.getName() + "=" + dbConnectionString);
        }//from www.j a va2 s. co  m
        param = mc.getParameter("db.driver");
        if (param != null) {
            dbDriver = (String) param.getValue();
            log.debug(param.getName() + "=" + dbDriver);
        }
        param = mc.getParameter("db.user");
        if (param != null) {
            dbUser = (String) param.getValue();
            log.debug(param.getName() + "=" + dbUser);
        }
        param = mc.getParameter("db.password");
        if (param != null) {
            dbPassword = (String) param.getValue();
            log.debug(param.getName() + "=" + dbPassword);
        }
    }

    this.transactionLock = new TransactionLock();
}

From source file:org.apache.jmeter.util.JsseSSLManager.java

/**
 * Create the SSLContext, and wrap all the X509KeyManagers with
 * our X509KeyManager so that we can choose our alias.
 *
 * @param provider/* w w  w.  ja  va 2  s.com*/
 *            Description of Parameter
 */
public JsseSSLManager(Provider provider) {
    log.debug("ssl Provider =  " + provider);
    setProvider(provider);
    if (null == this.rand) { // Surely this is always null in the constructor?
        this.rand = new SecureRandom();
    }
    try {
        if (SHARED_SESSION_CONTEXT) {
            log.debug("Creating shared context");
            this.defaultContext = createContext();
        } else {
            this.threadlocal = new ThreadLocal<>();
        }

        HttpsURLConnection.setDefaultSSLSocketFactory(new HttpSSLProtocolSocketFactory(this, CPS));
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        /*
         * Also set up HttpClient defaults
         */
        Protocol protocol = new Protocol(JsseSSLManager.HTTPS,
                (ProtocolSocketFactory) new HttpSSLProtocolSocketFactory(this, CPS), 443);
        Protocol.registerProtocol(JsseSSLManager.HTTPS, protocol);
        log.debug("SSL stuff all set");
    } catch (GeneralSecurityException ex) {
        log.error("Could not set up SSLContext", ex);
    }
    log.debug("JsseSSLManager installed");
}