List of usage examples for java.lang ThreadLocal ThreadLocal
public ThreadLocal()
From source file:org.danann.cernunnos.DynamicCacheHelper.java
public V getCachedObject(TaskRequest req, TaskResponse res, K key, Factory<K, V> factory) { final CacheMode cacheMode = CacheMode.valueOf((String) this.cacheModelPhrase.evaluate(req, res)); if (this.logger.isDebugEnabled()) { this.logger.debug("Getting cached object for '" + key + "' using cache mode " + cacheMode + " and factory " + factory); }// ww w . j ava 2s. com //Load the cache only if cache-all is enabled final ConcurrentMap<Tuple<Serializable, K>, Object> cache; final Tuple<Serializable, K> compoundCacheKey; switch (cacheMode) { case NONE: { return factory.createObject(key); } default: case ONE: { cache = null; compoundCacheKey = null; } break; case ALL: { cache = (ConcurrentMap<Tuple<Serializable, K>, Object>) this.cachePhrase.evaluate(req, res); final Serializable cacheNamespace = factory.getCacheNamespace(key); compoundCacheKey = new Tuple<Serializable, K>(cacheNamespace, key); } break; } //Determine the object to synchronize around final Object syncTarget = factory.getMutex(key); //get or create & cache the target object V instance = null; synchronized (syncTarget) { //Get the object from the local variables if no cache is available if (cache == null) { //Try for a thread-local instance first if (this.compareKeys(key, this.threadKeyHolder.get())) { instance = this.threadInstanceHolder.get(); } //Next try for a singleton instance else if (this.compareKeys(key, this.key)) { instance = this.instance; } } //Look in the passed cache for the instance else { final Object object = cache.get(compoundCacheKey); //If the cached object is a ThreadLocal use it for the instance if (object instanceof ThreadLocal<?>) { instance = ((ThreadLocal<V>) object).get(); } //If not assume it is the instance else { instance = (V) object; } } //If no instance was found create and cache one if (instance == null) { instance = factory.createObject(key); final boolean threadSafe = factory.isThreadSafe(key, instance); if (this.logger.isDebugEnabled()) { this.logger.debug( "Cache miss for '" + key + "' created '" + instance + "' threadSafe=" + threadSafe); } //If no cache is available store the instance in the local variables if (cache == null) { if (threadSafe) { this.instance = instance; this.key = key; } else { this.threadInstanceHolder.set(instance); this.threadKeyHolder.set(key); } } //Cache available store there else { if (threadSafe) { cache.put(compoundCacheKey, instance); } else { ThreadLocal<V> threadInstanceHolder = (ThreadLocal<V>) cache.get(compoundCacheKey); if (threadInstanceHolder == null) { threadInstanceHolder = new ThreadLocal<V>(); while (true) { Object existing = cache.putIfAbsent(compoundCacheKey, threadInstanceHolder); if (existing == null) { //nothing existed for that key, put was successful break; } if (existing instanceof ThreadLocal) { //Existing ThreadLocal, just use it threadInstanceHolder = (ThreadLocal) existing; break; } //something other than a ThreadLocal already exists, try replacing with the ThreadLocal final boolean replaced = cache.replace(compoundCacheKey, threadInstanceHolder, existing); if (replaced) { //Replace worked! break; } //Replace didn't work, try the whole process again, yay non-blocking! } if (cache instanceof EvictionAwareCache) { ((EvictionAwareCache) cache) .registerCacheEvictionListener(ThreadLocalCacheEvictionListener.INSTANCE); } } threadInstanceHolder.set(instance); } } } else if (this.logger.isDebugEnabled()) { this.logger.debug("Cache hit for '" + key + "' using '" + instance + "'"); } } return instance; }
From source file:org.jahia.services.content.rules.RulesListener.java
public RulesListener() { instances.add(this); dslFiles = new CopyOnWriteArrayList<Resource>(); globalObjects = new ConcurrentHashMap<String, Object>(); inRules = new ThreadLocal<Boolean>(); modulePackageNameMap = new ConcurrentHashMap<String, String>(); }
From source file:org.opencms.gwt.CmsGwtService.java
/** * Sets the current cms context.<p> * * @param cms the current cms context to set */// w w w . j a va 2 s .co m public synchronized void setCms(CmsObject cms) { if (m_perThreadCmsObject == null) { m_perThreadCmsObject = new ThreadLocal<CmsObject>(); } m_perThreadCmsObject.set(cms); }
From source file:org.codice.alliance.transformer.nitf.NitfPreStoragePlugin.java
private BufferedImage renderImage(ContentItem contentItem) throws IOException, ParseException, NitfFormatException { final ThreadLocal<BufferedImage> bufferedImage = new ThreadLocal<>(); if (contentItem != null && contentItem.getInputStream() != null) { NitfRenderer renderer = new NitfRenderer(); new NitfParserInputFlow().inputStream(contentItem.getInputStream()).allData() .forEachImageSegment(segment -> { if (bufferedImage.get() == null) { try { bufferedImage.set(renderer.render(segment)); } catch (IOException e) { LOGGER.error(e.getMessage(), e); }/*from w w w .java2 s.co m*/ } }); } return bufferedImage.get(); }
From source file:org.jboss.dashboard.profiler.Profiler.java
public Profiler() { runOnStart = false;//from w ww . j a v a 2 s. c o m running = false; idleTimeInMillis = 100; maxThreadProfilingTimeMillis = 300000; maxThreadStackTraceLength = 500; activeThreads = new ArrayList(); completedThreads = new ArrayList(); completedThreadsMinTimeMillis = 60000; completedThreadsMaxSize = 100; completedThreadsErrorsEnabled = true; completedThreadsFilter = new ThreadProfileFilter(); minCodeTraceTimeMillis = 10; currentThreadProfile = new ThreadLocal(); }
From source file:org.codice.alliance.nsili.common.ResultDAGConverter.java
public static DAG convertResult(Result result, ORB orb, POA poa, List<String> resultAttributes, Map<String, List<String>> mandatoryAttributes) throws DagParsingException { Double distanceInMeters = result.getDistanceInMeters(); Double resultScore = result.getRelevanceScore(); Metacard metacard = result.getMetacard(); DAG dag = new DAG(); DirectedAcyclicGraph<Node, Edge> graph = new DirectedAcyclicGraph<>(Edge.class); ProductImpl productImpl = new ProductImpl(); String id = result.getMetacard().getId(); if (!CorbaUtils.isIdActive(poa, id.getBytes(Charset.forName(ENCODING)))) { try {/*from w w w .j a va 2 s . c o m*/ poa.activate_object_with_id(id.getBytes(Charset.forName(ENCODING)), productImpl); } catch (ServantAlreadyActive | ObjectAlreadyActive | WrongPolicy e) { LOGGER.info("Convert DAG : Unable to activate product impl object ({}): {}", result.getMetacard().getId(), e.getLocalizedMessage()); } } org.omg.CORBA.Object obj = poa.create_reference_with_id(id.getBytes(Charset.forName(ENCODING)), ProductHelper.id()); Product product = ProductHelper.narrow(obj); Node productNode = createRootNode(orb); String attributeName = NsiliConstants.NSIL_PRODUCT; Any productAny = orb.create_any(); ProductHelper.insert(productAny, product); productNode.value = productAny; graph.addVertex(productNode); List<String> addedAttributes = new ArrayList<>(); addedAttributes.addAll(addCardNodeWithAttributes(graph, productNode, metacard, orb, attributeName + ":", resultAttributes)); addedAttributes.addAll(addFileNodeWithAttributes(graph, productNode, metacard, orb, attributeName + ":", resultAttributes)); addedAttributes.addAll(addSecurityNodeWithAttributes(graph, productNode, metacard, orb, attributeName + ":", resultAttributes)); addedAttributes.addAll(addMetadataSecurityNodeWithAttributes(graph, productNode, metacard, orb, attributeName + ":", resultAttributes)); addedAttributes.addAll(addParts(graph, productNode, metacard, orb, attributeName + ":", resultAttributes)); if (metacard.getThumbnail() != null && metacard.getThumbnail().length > 0) { addedAttributes.addAll(addThumbnailRelatedFile(graph, productNode, metacard, orb, attributeName + ":", resultAttributes)); } if (mandatoryAttributes != null && !mandatoryAttributes.isEmpty()) { final ThreadLocal<Boolean> dataIsValid = new ThreadLocal<>(); dataIsValid.set(true); Map<String, List<String>> addedAttrMap = getAttrMap(addedAttributes); addedAttrMap.entrySet().stream().forEach(entry -> dataIsValid.set(dataIsValid.get() && processEntry(entry.getKey(), mandatoryAttributes.get(entry.getKey()), entry.getValue()))); if (!dataIsValid.get()) { throw new DagParsingException("One or more mandatory attributes is missing on outgoing data"); } } graph.addVertex(productNode); NsiliCommonUtils.setUCOEdgeIds(graph); NsiliCommonUtils.setUCOEdges(productNode, graph); dag.edges = NsiliCommonUtils.getEdgeArrayFromGraph(graph); dag.nodes = NsiliCommonUtils.getNodeArrayFromGraph(graph); return dag; }
From source file:org.opencms.gwt.CmsGwtService.java
/** * Sets the current request.<p>//w w w.j a v a 2 s. c o m * * @param request the request to set */ public synchronized void setRequest(HttpServletRequest request) { if (perThreadRequest == null) { perThreadRequest = new ThreadLocal<HttpServletRequest>(); } perThreadRequest.set(request); }
From source file:dk.statsbiblioteket.util.xml.XSLT.java
private static ThreadLocal<Map<String, Transformer>> createLocalMapCache() { return new ThreadLocal<Map<String, Transformer>>() { private AtomicInteger counter = new AtomicInteger(0); @Override// w w w . j a v a 2 s .com protected Map<String, Transformer> initialValue() { log.trace("Creating ThreadLocal localMapCache #" + counter); return new HashMap<String, Transformer>(); } }; }
From source file:hudson.plugins.clearcase.AbstractClearCaseScm.java
private synchronized ThreadLocal<String> getNormalizedViewNameThreadLocalWrapper() { if (null == normalizedViewName) { this.normalizedViewName = new ThreadLocal<String>(); }/*from w w w .j a v a2 s . c o m*/ return this.normalizedViewName; }
From source file:au.org.ala.names.search.ALANameSearcher.java
/** * Creates a new name searcher. Using the indexDirectory * as the source directory/*from w w w. java2 s .c o m*/ * * @param indexDirectory The directory that contains the index files for the scientific names, irmng and vernacular names. * @throws CorruptIndexException * @throws IOException */ public ALANameSearcher(String indexDirectory) throws CorruptIndexException, IOException { //Initialis CB index searching items log.debug("Creating the search object for the name matching api..."); //make the query parsers thread safe queryParser = new ThreadLocal<QueryParser>() { @Override protected QueryParser initialValue() { QueryParser qp = new QueryParser(Version.LUCENE_34, "genus", new LowerCaseKeywordAnalyzer()); qp.setFuzzyMinSim(0.8f); //fuzzy match similarity setting. used to match the authorship. return qp; } }; idParser = new ThreadLocal<QueryParser>() { @Override protected QueryParser initialValue() { return new QueryParser(Version.LUCENE_34, "lsid", new org.apache.lucene.analysis.core.KeywordAnalyzer()); } }; cbReader = DirectoryReader.open(FSDirectory.open(createIfNotExist(indexDirectory + File.separator + "cb")));//false cbSearcher = new IndexSearcher(cbReader); //Initalise the IRMNG index searching items irmngReader = DirectoryReader .open(FSDirectory.open(createIfNotExist(indexDirectory + File.separator + "irmng"))); irmngSearcher = new IndexSearcher(irmngReader); //initalise the Common name index searching items vernReader = DirectoryReader .open(FSDirectory.open(createIfNotExist(indexDirectory + File.separator + "vernacular"))); vernSearcher = new IndexSearcher(vernReader); //initialise the identifier index idSearcher = new IndexSearcher( DirectoryReader.open(FSDirectory.open(createIfNotExist(indexDirectory + File.separator + "id")))); tnse = new TaxonNameSoundEx(); parser = new PhraseNameParser(); crossRankHomonyms = au.org.ala.names.util.FileUtils.streamToSet( this.getClass().getClassLoader().getResourceAsStream("au/org/ala/homonyms/cross_rank_homonyms.txt"), new java.util.HashSet<String>(), true); }