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.qrmedia.commons.persistence.hibernate.clone.HibernateEntityGraphClonerTest.java

@SuppressWarnings("unchecked")
@Test//w w w . j a  v a  2 s .  c o  m
public void clone_entities() throws IllegalAccessException {
    final StubHibernateEntity entity1 = new StubHibernateEntity();

    String property = "007";
    final StubHibernateEntity relatedEntity = new SimplePropertyEqualStubHibernateEntity(property);
    entity1.setNonSimpleBeanProperty(relatedEntity);

    Set<StubHibernateEntity> nonSimpleCollectionBeanProperty = new HashSet<StubHibernateEntity>();

    // reuse relatedEntity to check if its clone is used in both places
    nonSimpleCollectionBeanProperty.add(relatedEntity);
    entity1.setNonSimpleCollectionBeanProperty(nonSimpleCollectionBeanProperty);

    // the first call to the bean cloner creates a clone, adds a new entity and some commands
    final GraphWiringCommand graphWiringCommand1 = createMock(GraphWiringCommand.class);
    final GraphPostProcessingCommand graphPostProcessingCommand = createMock(GraphPostProcessingCommand.class);
    final StubHibernateEntity clone1 = new StubHibernateEntity();
    entityBeanCloner.visitNode(eq(new EntityPreserveIdFlagPair(entity1, false)), same(entityGraphCloner),
            (IdentityHashMap<Object, Object>) anyObject());
    expectLastCall()
            .andAnswer(new HibernateEntityBeanClonerActions(entity1, clone1, Arrays.asList(relatedEntity),
                    Arrays.asList(graphWiringCommand1), Arrays.asList(graphPostProcessingCommand)));

    // note that entity2 is equal to (but not identical to) relatedEntity!
    final GraphWiringCommand graphWiringCommand2 = createMock(GraphWiringCommand.class);
    final StubHibernateEntity entity2 = new SimplePropertyEqualStubHibernateEntity(property);
    entity2.setNonSimpleBeanProperty(entity1);
    final StubHibernateEntity clone2 = new SimplePropertyEqualStubHibernateEntity(property);
    entityBeanCloner.visitNode(eq(new EntityPreserveIdFlagPair(entity2, false)), same(entityGraphCloner),
            (IdentityHashMap<Object, Object>) anyObject());
    expectLastCall().andAnswer(new HibernateEntityBeanClonerActions(entity2, clone2, null,
            Arrays.asList(graphWiringCommand2), null));

    final StubHibernateEntity relatedEntityClone = new SimplePropertyEqualStubHibernateEntity(property);
    entityBeanCloner.visitNode(eq(new EntityPreserveIdFlagPair(relatedEntity, false)), same(entityGraphCloner),
            (IdentityHashMap<Object, Object>) anyObject());
    expectLastCall().andAnswer(new HibernateEntityBeanClonerActions(relatedEntity, relatedEntityClone));

    // use flags mutable for the mocks to track the order of calls
    final ThreadLocal<Integer> numGraphWiringCommandExecuted = new ThreadLocal<Integer>();
    numGraphWiringCommandExecuted.set(0);

    // the entity graph cloner should call the commands in the order they were added

    graphWiringCommand1.forEntities();
    expectLastCall().andReturn(Arrays.asList(entity1));
    graphWiringCommand1.execute(MapUtils.toMap(new IdentityHashMap<Object, Object>(), entity1, clone1));
    expectLastCall().andAnswer(new NumGraphWiringCommandsExecutedVerifier(numGraphWiringCommandExecuted, 0));

    graphWiringCommand2.forEntities();
    expectLastCall().andReturn(Arrays.asList(relatedEntity));
    graphWiringCommand2
            .execute(MapUtils.toMap(new IdentityHashMap<Object, Object>(), relatedEntity, relatedEntityClone));
    expectLastCall().andAnswer(new NumGraphWiringCommandsExecutedVerifier(numGraphWiringCommandExecuted, 1));

    // this *must* be called after all the wiring commands have been completed
    graphPostProcessingCommand.execute();
    expectLastCall().andAnswer(new IAnswer<Object>() {

        public Object answer() throws Throwable {

            if (!(numGraphWiringCommandExecuted.get() == 2)) {
                fail("Graph post-processing command executed before wiring was complete.");
            }

            return null;
        }

    });

    replay(entityBeanCloner, graphWiringCommand1, graphWiringCommand2, graphPostProcessingCommand);

    Map<StubHibernateEntity, StubHibernateEntity> clones = entityGraphCloner
            .clone(Arrays.asList(entity1, entity2));
    assertEquals(MapUtils.<StubHibernateEntity, StubHibernateEntity>toMap(entity1, clone1, entity2, clone2),
            clones);

    verify(entityBeanCloner, graphWiringCommand1, graphWiringCommand2, graphPostProcessingCommand);

    // check that any internal state maintained during the cloning has been cleaned up
    assertTrue(ReflectionUtils.<List<?>>getValue(entityGraphCloner, "graphWiringCommands").isEmpty());
    assertTrue(ReflectionUtils.<List<?>>getValue(entityGraphCloner, "graphPostProcessingCommands").isEmpty());

    /*
     * The actual wiring of the objects is *not* checked because that is the function
     * of the command objects, *not* the entity graph cloner.
     * As such, this is not within the scope of a unit test.
     */
}

From source file:com.mmnaseri.dragonfly.data.impl.DefaultDataAccess.java

public DefaultDataAccess(DataAccessSession session, EntityContext entityContext,
        EntityHandlerContext entityHandlerContext, boolean autoInitialize) {
    this.session = session;
    this.entityContext = entityContext;
    this.entityHandlerContext = entityHandlerContext;
    this.beanInitializer = new ConstructorBeanInitializer();
    this.metadataCollector = new ColumnMappingMetadataCollector();
    this.eventHandler = new CompositeDataAccessEventHandler();
    this.initializationContext = new ThreadLocalEntityInitializationContext(this);
    this.rowHandler = new DefaultRowHandler();
    this.mapCreator = new DefaultEntityMapCreator();
    try {// ww  w.  j  av  a  2 s . c om
        this.entityCreator = new DefaultMapEntityCreator();
    } catch (RegistryException e) {
        throw new DataAccessSessionInitializationError("Failed to initialize the map-to-entity converter", e);
    }
    this.saveQueue = new ThreadLocal<Map<Object, Object>>() {
        @Override
        protected Map<Object, Object> initialValue() {
            return new HashMap<Object, Object>();
        }
    };
    this.deleteQueue = new ThreadLocal<Set<Object>>() {
        @Override
        protected Set<Object> initialValue() {
            return new HashSet<Object>();
        }
    };
    this.deleteAllStatements = new ThreadLocal<Map<Class<?>, Map<Statements.Manipulation, Set<Statement>>>>() {
        @Override
        protected Map<Class<?>, Map<Statements.Manipulation, Set<Statement>>> initialValue() {
            return new HashMap<Class<?>, Map<Statements.Manipulation, Set<Statement>>>();
        }
    };
    this.batchOperation = new ThreadLocal<List<BatchOperationDescriptor>>();
    this.batch = new ThreadLocal<Boolean>() {
        @Override
        protected Boolean initialValue() {
            return false;
        }
    };
    this.entityContext.initialize(this);
    this.statementPreparator = new DefaultStatementPreparator(false);
    this.deferredKeys = new ThreadLocal<List<Object>>() {
        @Override
        protected List<Object> initialValue() {
            return new ArrayList<Object>();
        }
    };
    this.deferredSaveQueue = new ThreadLocal<Set<Object>>() {
        @Override
        protected Set<Object> initialValue() {
            return new HashSet<Object>();
        }
    };
    this.saveQueueLock = new ThreadLocal<Long>() {
        @Override
        protected Long initialValue() {
            return 0L;
        }
    };
    this.localCounts = new ThreadLocal<Set<LocalOperationResult>>() {
        @Override
        protected Set<LocalOperationResult> initialValue() {
            return new HashSet<LocalOperationResult>();
        }
    };
    this.localStatements = new ThreadLocal<Stack<PreparedStatement>>() {
        @Override
        protected Stack<PreparedStatement> initialValue() {
            return new Stack<PreparedStatement>();
        }
    };
    if (autoInitialize) {
        log.info("Automatically initializing the session");
        synchronized (this.session) {
            if (!this.session.isInitialized()) {
                this.session.initialize();
                this.session.markInitialized();
            }
        }
    }
}

From source file:SoundManagerTest.java

/**
 * Creates a new SoundManager with the specified maximum number of
 * simultaneous sounds./*w  w  w  .j a  v  a2s.co m*/
 */
public SoundManager(AudioFormat playbackFormat, int maxSimultaneousSounds) {
    super(Math.min(maxSimultaneousSounds, getMaxSimultaneousSounds(playbackFormat)));
    this.playbackFormat = playbackFormat;
    localLine = new ThreadLocal();
    localBuffer = new ThreadLocal();
    pausedLock = new Object();
    // notify threads in pool it's ok to start
    synchronized (this) {
        notifyAll();
    }
}

From source file:org.araneaframework.core.BaseComponent.java

private void incCallCount() {
    if (reentrantTLS == null)
        reentrantTLS = new ThreadLocal();

    if (reentrantTLS.get() == null)
        reentrantTLS.set(new Counter(0));

    callCount++;/*from  www  . ja va  2 s  . co  m*/
    ((Counter) reentrantTLS.get()).counter++;

    if (getReentrantCount() > 1)
        reentrantCallCount++;
}

From source file:biz.c24.io.spring.batch.reader.C24ItemReader.java

/**
 * Clean up any resources we're consuming
 *//*from  w  w w .j a  v a  2 s.  c  o  m*/
@AfterStep
public void cleanup() {
    if (validator != null) {
        validator = new ThreadLocal<ValidationManager>();
    }
    source.close();
}

From source file:com.linkedin.pinot.integration.tests.HybridClusterScanComparisonIntegrationTest.java

protected void runQueryAsync(final String pqlQuery, final String scanResult) {
    _queryExecutor.execute(new Runnable() {
        @Override//from w  ww  .  ja  va2 s.com
        public void run() {
            final ScanBasedQueryProcessor scanBasedQueryProcessor = (new ThreadLocal<ScanBasedQueryProcessor>() {
                @Override
                public ScanBasedQueryProcessor get() {
                    return _scanBasedQueryProcessor.clone();
                }
            }).get();

            try {
                runQuery(pqlQuery, scanBasedQueryProcessor, false, scanResult);
            } catch (Exception e) {
                Assert.fail("Caught exception", e);
            }
        }
    });
}

From source file:org.codice.alliance.plugin.nitf.NitfPostIngestPlugin.java

private BufferedImage render(InputStream inputStream,
        Function<Pair<ImageSegment, NitfRenderer>, BufferedImage> imageSegmentFunction)
        throws NitfFormatException {

    final ThreadLocal<BufferedImage> bufferedImage = new ThreadLocal<>();

    if (inputStream != null) {
        NitfRenderer renderer = getNitfRenderer();
        nitfParserService.parseNitf(inputStream, true).forEachImageSegment(segment -> {
            if (bufferedImage.get() == null) {
                BufferedImage bi = imageSegmentFunction.apply(new ImmutablePair<>(segment, renderer));
                if (bi != null) {
                    bufferedImage.set(bi);
                }/*from  w ww  . j  a v a 2  s.  co m*/
            }
        }).end();
    }

    return bufferedImage.get();
}

From source file:de.codesourcery.eve.apiclient.parsers.AbstractResponseParser.java

/**
 * Returns a thread-local <code>DateFormat</code>
 * instance for parsing date strings returned
 * by the API server.//from w w  w.  j av  a2s .  com
 * 
 * @return
 */
protected DateFormat getDateFormat() {
    /*
     * TODO: Hack to circumvent a 
     * bug with EasyMock partial mocking, somehow
     * final instance fields are not initialized by CGLib and
     * since the constructor doesn't seem to be run as well...
     */
    final SimpleDateFormat result;
    if (this.DATE_FORMAT == null) {
        result = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        this.DATE_FORMAT = new ThreadLocal<SimpleDateFormat>();
        DATE_FORMAT.set(result);
    } else {
        result = this.DATE_FORMAT.get();
    }
    return result;
}

From source file:com.aol.advertising.qiao.emitter.AMQEmitter.java

@Override
public void suspend() {
    if (isSuspended.compareAndSet(false, true)) {
        localProducer = new ThreadLocal<Producer>();
    }
}

From source file:org.nuxeo.ecm.core.io.registry.reflect.MarshallerInspector.java

/**
 * Create or get a thread local instance of the marshaller.
 *
 * @param ctx The {@link RenderingContext} to inject.
 * @return An instance of the marshaller.
 * @since 7.2//  ww  w  . j a v  a 2  s. co m
 */
private Object getThreadInstance(RenderingContext ctx) {
    if (threadInstance == null) {
        threadInstance = new ThreadLocal<Object>();
    }
    Object instance = threadInstance.get();
    if (instance == null) {
        instance = getNewInstance(ctx, false);
        threadInstance.set(instance);
    } else {
        for (Field contextField : contextFields) {
            try {
                contextField.set(instance, ctx);
            } catch (IllegalArgumentException | IllegalAccessException e) {
                throw new NuxeoException("unable to create a marshaller instance for clazz " + clazz.getName(),
                        e);
            }
        }
    }
    return instance;
}