Java 类org.springframework.core.NamedThreadLocal 实例源码

项目:matsuo-core    文件:WideSessionScope.java   
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
  try {
    Object mutex = RequestContextHolder.currentRequestAttributes().getSessionMutex();
    synchronized (mutex) {
      return super.get(name, objectFactory);
    }
  } catch (IllegalStateException e) {
    logger.debug("outside web session");
    ThreadLocal<Object> objectHolder = objectHolders.get(name);
    if (objectHolder == null) {
      objectHolders.put(name, new NamedThreadLocal<>("wideScopeObjectHolder_" + name));
      objectHolder = objectHolders.get(name);
    }

    if (objectHolder.get() == null) {
      objectHolder.set(objectFactory.getObject());
    }
    return objectHolder.get();
  }
}
项目:pinenut    文件:ThreadLocalTest.java   
@Test
public void test(){
    final ThreadLocal<Object> prototypesCurrentlyInCreation =
            new NamedThreadLocal<Object>("Prototype beans currently in creation");

    Assert.assertNull(prototypesCurrentlyInCreation.get());
    prototypesCurrentlyInCreation.set("abc");
    Assert.assertNotNull(prototypesCurrentlyInCreation.get());
    prototypesCurrentlyInCreation.set(new HashSet<String>());
    Assert.assertNotNull(prototypesCurrentlyInCreation.get());
    prototypesCurrentlyInCreation.remove();
    Assert.assertNull(prototypesCurrentlyInCreation.get());
    System.out.println(prototypesCurrentlyInCreation.toString());
}