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:org.apache.pig.backend.hadoop.executionengine.tez.PigProcessor.java

@Override
public void close() throws Exception {
    // Avoid memory leak. ThreadLocals especially leak a lot of memory.
    // The Reporter and Context objects hold TezProcessorContextImpl
    // which holds input and its sort buffers which are huge.
    PhysicalOperator.reporter = new ThreadLocal<PigProgressable>();
    PigMapReduce.sJobConfInternal = new ThreadLocal<Configuration>();
    PigMapReduce.sJobContext = null;//  w  w  w.j  a  v  a  2 s  .  co  m
    PigContext.setPackageImportList(null);
    UDFContext.destroy();
    execPlan = null;
    fileOutputs = null;
    leaf = null;
    conf = null;
    sampleMap = null;
    sampleVertex = null;
    if (pigHadoopLogger != null) {
        pigHadoopLogger.destroy();
        pigHadoopLogger = null;
    }
}

From source file:org.arrow.runtime.execution.Execution.java

public void setCurrentEventMessage(EventMessage currentEventMessage) {
    if (this.currentEventMessage == null) {
        this.currentEventMessage = new ThreadLocal<>();
    }//from ww w .  j  a  v  a 2  s. c  om
    this.currentEventMessage.set(currentEventMessage);
}

From source file:org.squale.jraf.provider.persistence.hibernate.PersistenceProviderImpl.java

public ISession getSession() throws JrafPersistenceException {

    SessionImpl lc_session = null;/*from   www .jav  a 2  s .  c  om*/

    if (sessions != null) {

        try {

            // cas Thread local session
            if (isThreadLocalSession()) {

                if (log.isDebugEnabled()) {
                    log.debug("Cas Thread Local Session...");
                }

                // on cree un thread local si il n'existe pas
                if (getThreadLocal() == null) {
                    setThreadLocal(new ThreadLocal());
                }

                // recuperation de la session du thread local
                lc_session = (SessionImpl) threadLocal.get();
                if (lc_session == null) {
                    if (log.isDebugEnabled()) {
                        log.debug("Cas session null...");
                    }

                    // creation de la session
                    lc_session = new SessionImpl(sessions.openSession(), this);
                    // on met la session dans le thread local
                    threadLocal.set(lc_session);
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Cas session deja creee...");
                    }

                    // cas session longue
                    if (isLongSession()) {
                        if (log.isDebugEnabled()) {
                            log.debug("Cas session longue...");
                        }

                        // reconnexion de la session si besoin
                        if (!lc_session.getSession().isConnected()) {
                            if (log.isDebugEnabled()) {
                                log.debug("Connexion de la session...");
                            }
                            // Depsuis hibernate 3 plus besoin de faire de reconnect et disconnect 
                            //                     lc_session.getSession().reconnect();
                        }

                    }
                }

                // cas transaction automatique
                if (isAutomaticTransaction()) {
                    if (log.isDebugEnabled()) {
                        log.debug("Cas transaction automatique...");
                    }

                    if (!lc_session.isInTransaction()) {
                        if (log.isDebugEnabled()) {
                            log.debug("Pas de transaction existante...");
                            log.debug("Demarrage d'une transaction...");
                        }

                        lc_session.beginTransaction();
                    }

                }

            }
            // cas simple
            // pas de thread local session
            else {
                if (log.isDebugEnabled()) {
                    log.debug("Cas simple...");
                    log.debug("Creation d'une nouvelle session...");
                }
                // initialisation de la session
                lc_session = new SessionImpl(sessions.openSession(), this);
            }

            return lc_session;

        } catch (Exception e) {
            String message = "La demande d'une nouvelle session hibernate a chou  cause d'un problme de SGBD";
            log.fatal(message, e);
            throw new JrafPersistenceException(message, e);
        }

    } else {
        log.fatal(
                "La demande d'une nouvelle session hibernate a chou. Erreur : l'objet sessions hibernate est null");
        throw new JrafPersistenceException(
                "La demande d'une nouvelle session hibernate a chou. Erreur : l'objet sessions hibernate est null");
    }
}

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

/**
 * Set whether or not you want validation to be performed on the parsed CDOs. 
 * An exception will be thrown for any entity which fails validation.
 * // w ww  .  ja v a2 s.c o m
 * @param validate Whether or not to validate parsed CDOs
 */
public void setValidate(boolean validate) {
    validator = validate ? new ThreadLocal<ValidationManager>() : null;
}

From source file:de.tudarmstadt.lt.ltbot.postprocessor.DecesiveValueProducerPerplexity.java

private boolean connectStringProviderService() {
    LOG.info(/* w  w w  . ja  va  2 s .  c  o  m*/
            String.format("Connecting to service rmi://%s:%d/%s.", getRmihost(), getRmiport(), getServiceID()));
    if (_lmprvdr == null) {
        _lmprvdr = new ThreadLocal<StringProviderMXBean>() {
            @Override
            protected StringProviderMXBean initialValue() {
                return AbstractStringProvider.connectToServer(getRmihost(), getRmiport(), getServiceID());
            }
        };
    } else {
        _lmprvdr.set(AbstractStringProvider.connectToServer(getRmihost(), getRmiport(), getServiceID()));
    }
    if (_lmprvdr.get() == null) {
        LOG.severe(String.format("Could not connect to service rmi://%s:%d/%s.", getRmihost(), getRmiport(),
                getServiceID()));
        return false;
    }
    LOG.info(String.format("Connected to service rmi://%s:%d/%s.", getRmihost(), getRmiport(), getServiceID()));
    return true;
}

From source file:com.jfastnet.AbstractTest.java

public Config newClientConfig() {
    ThreadLocal<Kryo> kryos = new ThreadLocal<Kryo>() {
        protected Kryo initialValue() {
            Kryo kryo = new Kryo();
            kryo.setInstantiatorStrategy(new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy()));
            customizeKryo(kryo);/*  ww w . ja v a  2  s. c o m*/
            return kryo;
        }
    };
    Config config = new Config();
    config.host = "localhost";
    config.port = 15150;
    config.bindPort = 0;
    config.connectTimeout = 10000;
    config.serialiser = new KryoSerialiser(new SerialiserConfig(), kryos);
    config.udpPeerClass = JavaNetPeer.class;
    //      config.udpPeer = new KryoNettyPeer(config);
    config.externalReceiver = message1 -> message1.process(null);
    config.keepAliveInterval = 700;
    config.getAdditionalConfig(
            MessageLogProcessor.ProcessorConfig.class).messageLogReceiveFilter = message -> true;
    config.compressBigMessages = true;
    config.autoSplitTooBigMessages = true;

    return (config);
}

From source file:com.jaspersoft.jasperserver.api.metadata.common.service.impl.hibernate.HibernateRepositoryServiceImpl.java

public HibernateRepositoryServiceImpl() {
    tempNameResources = new ThreadLocal();
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

private PersistenceHelper(TYPE t, String unitName) {
    startLicenseCheck();//from   ww w.j  av  a 2s  .c  o m

    this.type = t;
    try {
        emf = Persistence.createEntityManagerFactory(unitName);
        emByThread = new ThreadLocal<EntityManager>();
    } catch (Exception ee) {
        logger.log(Level.SEVERE, "Exception while init Persistence.xml...", ee);
        throw new RuntimeException(ee);
    }
    if (this.type.equals(TYPE.JTA)) {
        try {
            Context c = new InitialContext();
            tx = new JtaTransaction((UserTransaction) c.lookup("java:comp/UserTransaction"));
        } catch (NamingException e) {
            logger.log(Level.SEVERE, "Exception while initializing PersistenceHelper in JTA...", e);
            type = TYPE.LOCAL;
        }
    }
    if (emf.getMetamodel().getEntities() != null && !emf.getMetamodel().getEntities().isEmpty()) {
        for (EntityType e : emf.getMetamodel().getEntities()) {
            try {
                initClassMapping(e.getBindableJavaType().getName());
            } catch (Exception e1) {
                logger.log(Level.SEVERE, "Exception", e1);
            }
        }
    }
    endLicenseCheck();

}

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

private BufferedImage render(ContentItem contentItem,
        Function<Pair<ImageSegment, NitfRenderer>, BufferedImage> imageSegmentFunction)
        throws IOException, ParseException, NitfFormatException {

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

    if (contentItem != null) {
        InputStream inputStream = contentItem.getInputStream();

        if (inputStream != null) {
            try {
                NitfRenderer renderer = getNitfRenderer();

                new NitfParserInputFlowImpl().inputStream(inputStream).allData()
                        .forEachImageSegment(segment -> {
                            if (bufferedImage.get() == null) {
                                BufferedImage bi = imageSegmentFunction
                                        .apply(new ImmutablePair<>(segment, renderer));
                                if (bi != null) {
                                    bufferedImage.set(bi);
                                }/*ww  w  .  j  a v  a2s .  c  o m*/
                            }
                        }).end();
            } finally {
                IOUtils.closeQuietly(inputStream);
            }
        }
    }

    return bufferedImage.get();
}

From source file:com.springsense.nutch.indexer.SpringSenseIndexingFilter.java

public ThreadLocal<Disambiguator> getDisambiguatorStore() {
    if (disambiguatorStore == null) {
        disambiguatorStore = new ThreadLocal<Disambiguator>() {

            @Override//w w  w  .j a v a2  s .  co m
            protected Disambiguator initialValue() {
                try {
                    LOG.info("Opening a new disambiguator for this thread.");
                    return (getDisambiguatorFactory().openNewDisambiguator());
                } catch (IOException e) {
                    throw new RuntimeException("Could not create new disambiguator due to an error", e);
                }
            }

        };
    }
    return disambiguatorStore;
}