List of usage examples for java.lang ThreadLocal set
public void set(T value)
From source file:org.exoplatform.social.core.storage.impl.RelationshipStorageImpl.java
private String[] getRelationships(String id) { ThreadLocal<String[]> identityIdsLocal = new ThreadLocal<String[]>(); String[] relationshipIds = new String[0]; identityIdsLocal.set(relationshipIds); try {/*from w w w . j a v a2s .c o m*/ IdentityEntity identityEntity = _findById(IdentityEntity.class, id); StringBuffer sb = new StringBuffer().append("SELECT * FROM soc:relationshipdefinition WHERE "); sb.append(JCRProperties.path.getName()).append(" LIKE '") .append(identityEntity.getPath() + StorageUtils.SLASH_STR + StorageUtils.PERCENT_STR) .append("'"); // sb.append(" ORDER BY ").append(RelationshipEntity.createdTime.getName()).append(" DESC "); synchronized (lock) { NodeIterator it = nodes(sb.toString()); while (it.hasNext()) { Node node = (Node) it.next(); RelationshipEntity currentRelationshipEntity = _findById(RelationshipEntity.class, node.getUUID()); IdentityEntity gotIdentityEntity; if (currentRelationshipEntity.isReceiver()) { gotIdentityEntity = currentRelationshipEntity.getFrom(); } else { gotIdentityEntity = currentRelationshipEntity.getTo(); } identityIdsLocal .set((String[]) ArrayUtils.add(identityIdsLocal.get(), gotIdentityEntity.getId())); } } } catch (Exception e) { throw new RelationshipStorageException(RelationshipStorageException.Type.FAILED_TO_GET_RELATIONSHIP, e.getMessage()); } return identityIdsLocal.get(); }
From source file:org.jsweet.transpiler.JSweetTranspiler.java
private void initExportedVarMap() throws Exception { Field f = Thread.currentThread().getContextClassLoader().loadClass("jsweet.util.Globals") .getDeclaredField("EXPORTED_VARS"); f.setAccessible(true);//from w w w . j a v a2 s .co m @SuppressWarnings("unchecked") ThreadLocal<Map<String, Object>> exportedVars = (ThreadLocal<Map<String, Object>>) f.get(null); exportedVars.set(new HashMap<>()); }
From source file:org.exoplatform.social.core.storage.impl.ActivityStreamStorageImpl.java
@Override public void update(ProcessContext ctx) { final ReentrantLock lock = new ReentrantLock(); ThreadLocal<Set<String>> idLocal = new ThreadLocal<Set<String>>(); try {/*from w ww .j a va2 s . c om*/ StreamProcessContext streamCtx = ObjectHelper.cast(StreamProcessContext.class, ctx); ExoSocialActivity activity = streamCtx.getActivity(); ActivityEntity activityEntity = _findById(ActivityEntity.class, activity.getId()); lock.lock(); // block until condition holds Collection<ActivityRef> references = activityEntity.getActivityRefs(); Set<String> ids = new ConcurrentSkipListSet<String>(); for (ActivityRef ref : references) { ids.add(ref.getId()); } idLocal.set(ids); Set<String> idList = idLocal.get(); if (idList.size() > 0) { for (String id : idList) { ActivityRef old = _findById(ActivityRef.class, id); LOG.debug("ActivityRef will be deleted: " + old.toString()); ActivityRefListEntity refList = old.getDay().getMonth().getYear().getList(); // if (refList.isOnlyUpdate(old, activity.getUpdated().getTime())) { old.setName("" + activity.getUpdated().getTime()); old.setLastUpdated(activity.getUpdated().getTime()); } else { ActivityRef newRef = refList.getOrCreated(activity.getUpdated().getTime()); newRef.setLastUpdated(activity.getUpdated().getTime()); newRef.setActivityEntity(activityEntity); getSession().remove(old); } } } // mentioners addMentioner(streamCtx.getMentioners(), activityEntity); //turnOffLock to get increase perf //turnOnUpdateLock = false; } catch (NodeNotFoundException ex) { LOG.warn("Probably was updated activity reference by another session"); LOG.debug(ex.getMessage(), ex); //turnOnLock to avoid next exception } catch (ChromatticException ex) { Throwable throwable = ex.getCause(); if (throwable instanceof ItemExistsException || throwable instanceof InvalidItemStateException || throwable instanceof PathNotFoundException) { LOG.warn("Probably was updated activity reference by another session"); LOG.debug(ex.getMessage(), ex); //turnOnLock to avoid next exception } else { LOG.warn("Probably was updated activity reference by another session", ex); LOG.debug(ex.getMessage(), ex); } } finally { getSession().save(); lock.unlock(); } }
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); }//from www .j a v a2 s .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:de.innovationgate.utils.WGUtils.java
/** * Method to clear a value inside a ThreadLocal. * This method will use the JDK5 method ThreadLocal.remove() when available to do this task. * This will allow the ThreadLocalMap-Entry to be garbage collected. Otherwise it sets the Entry to the value of null. * @param tl The ThreadLocal whose value to clear * @deprecated since Java 5 is minimum dependency of OpenWGA *//*from ww w .j a v a2 s. c o m*/ public static void removeThreadLocalValue(ThreadLocal<?> tl) { if (_threadLocalRemoveMethod != null) { try { _threadLocalRemoveMethod.invoke(tl, new Object[] {}); return; } catch (Exception e) { Logger.getLogger("wga.utils").error("Error removing thread local value", e); } } tl.set(null); }