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.aol.advertising.qiao.emitter.KafkaEmitter.java

@Override
public void suspend() {
    if (isSuspended.compareAndSet(false, true)) {
        threadLocalProducers = new ThreadLocal<KafkaProducer>();
    }//from ww w  . j av a2s.c o m
}

From source file:com.nextep.datadesigner.hibernate.HibernateUtil.java

/**
 * This method handles the case when we loose connection with the repository database. <br>
 * <b>MUST BE CALLED WITHIN THE UI THREAD</b>
 *///from  w  w  w . ja  v a2  s.  c  o m
public void reconnectAll() {
    // Closing everything we can
    for (Session s : new ArrayList<Session>(ALL_SESSIONS)) {
        try {
            s.close();
        } catch (RuntimeException e) {
            // It may always fail, but there is not much we could do
            // Even logging would be useless and would complexify our logs...
        }
        ALL_SESSIONS.remove(s);
    }

    // Don't do that at home...
    /*
     * We don't want any old session to be reused since we may have been disconnected from the
     * network. This is to avoid having the same critical network message for every repository
     * connection we are using.
     */
    sandBoxSession = new ThreadLocal<Session>();

    // Resetting our SessionFactory
    initSessionFactory();

    // Reconnecting our main and sandbox sessions
    mainSession = openCachedSession();
    openSandBoxSession();
}

From source file:org.apache.pig.backend.hadoop.executionengine.physicalLayer.PhysicalOperator.java

public static void staticDataCleanup() {
    reporter = new ThreadLocal<PigProgressable>();
}

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

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

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

    if (inputStream != null) {
        try {/*from   w  w  w .j  a  v a2 s .  c  om*/
            available.acquire();
            NitfRenderer renderer = nitfRendererSupplier.get();
            NitfParserInputFlow parserInputFlow = nitfParserSupplier.get();

            parserInputFlow.inputStream(inputStream).allData().forEachImageSegment(segment -> {
                if (bufferedImage.get() == null) {
                    BufferedImage bi = imageSegmentFunction.apply(new ImmutablePair<>(segment, renderer));
                    if (bi != null) {
                        bufferedImage.set(bi);
                    }
                }
            }).end();
        } finally {
            IOUtils.closeQuietly(inputStream);
            available.release();
        }
    }

    BufferedImage image = bufferedImage.get();
    bufferedImage.remove();
    return image;
}

From source file:com.espertech.esper.core.service.StatementResultServiceImpl.java

/**
 * Dispatches when the statement is stopped any remaining results.
 *///from   w ww  .j  ava 2  s .  c  o m
public void dispatchOnStop() {
    lastIterableEvent = null;
    ArrayDeque<UniformPair<EventBean[]>> dispatches = lastResults.get();
    if (dispatches.isEmpty()) {
        return;
    }
    execute();

    lastResults = new ThreadLocal<ArrayDeque<UniformPair<EventBean[]>>>() {
        protected synchronized ArrayDeque<UniformPair<EventBean[]>> initialValue() {
            return new ArrayDeque<UniformPair<EventBean[]>>();
        }
    };
}

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  ww  w . ja v  a2 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.voltdb.exportclient.ExportToFileClient.java

public ExportToFileClient(char delimiter, String nonce, File outdir, int period, String dateformatString,
        String fullDelimiters, int firstfield, boolean useAdminPorts, boolean batched, boolean withSchema,
        int throughputMonitorPeriod, boolean autodiscoverTopolgy) {
    super(useAdminPorts, throughputMonitorPeriod, autodiscoverTopolgy);
    m_delimiter = delimiter;//from   w  w  w .j  a  v a  2  s  . c om
    m_extension = (delimiter == ',') ? ".csv" : ".tsv";
    m_nonce = nonce;
    m_outDir = outdir;
    m_tableDecoders = new HashMap<Long, HashMap<String, ExportToFileDecoder>>();
    m_period = period;
    m_dateFormatOriginalString = dateformatString;
    // SimpleDateFormat isn't threadsafe
    // ThreadLocal variables should protect them, lamely.
    m_dateformat = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat(m_dateFormatOriginalString);
        }
    };
    m_ODBCDateformat = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat(ODBC_DATE_FORMAT_STRING);
        }
    };
    m_firstfield = firstfield;
    m_batched = batched;
    m_withSchema = withSchema;

    if (fullDelimiters != null) {
        fullDelimiters = StringEscapeUtils.unescapeHtml4(fullDelimiters);
        m_fullDelimiters = new char[4];
        for (int i = 0; i < 4; i++) {
            m_fullDelimiters[i] = fullDelimiters.charAt(i);
            //System.out.printf("FULL DELIMETER %d: %c\n", i, m_fullDelimiters[i]);
        }
    } else {
        m_fullDelimiters = null;
    }

    // init the batch system with the first batch
    assert (m_current == null);
    m_current = new PeriodicExportContext(new Date());

    // schedule rotations every m_period minutes
    TimerTask rotateTask = new TimerTask() {
        @Override
        public void run() {
            roll(new Date());
        }
    };
    m_timer.scheduleAtFixedRate(rotateTask, 1000 * 60 * m_period, 1000 * 60 * m_period);
}

From source file:org.jboss.dashboard.commons.filter.AbstractFilter.java

public FilterByCriteria cloneFilter() {
    try {/*from  ww w . j a  v a  2 s .  com*/
        AbstractFilter clone = (AbstractFilter) super.clone();
        clone._filterVarValues = new HashMap();
        clone._bshIntepreterThread = new ThreadLocal();
        clone.filterProperties = new ArrayList();
        Iterator it = filterProperties.iterator();
        while (it.hasNext()) {
            Object[] prop = (Object[]) it.next();
            Collection allowedValues = (Collection) prop[5];
            clone.filterProperties.add(new Object[] { prop[0], prop[1], prop[2], prop[3], prop[4],
                    allowedValues == null ? null : new ArrayList(allowedValues), prop[6], prop[7], prop[8] });
        }
        return clone;
    } catch (CloneNotSupportedException e) {
        log.error("Clone exception.", e);
        return null;
    }
}

From source file:org.kaaproject.kaa.server.appenders.cassandra.appender.CassandraLogEventDao.java

private String formatTs(String tsValue, ColumnMappingElement element) {
    if (tsValue == null) {
        long ts = System.currentTimeMillis();
        final String pattern = element.getValue();
        if (pattern == null || pattern.isEmpty()) {
            tsValue = ts + "";
        } else {//from www  .j  ava 2 s.c o  m
            ThreadLocal<SimpleDateFormat> formatterTL = dateFormatMap.get(pattern);
            if (formatterTL == null) {
                formatterTL = new ThreadLocal<SimpleDateFormat>() {
                    @Override
                    protected SimpleDateFormat initialValue() {
                        return new SimpleDateFormat(pattern);
                    }
                };
                dateFormatMap.putIfAbsent(pattern, formatterTL);
            }
            SimpleDateFormat formatter = formatterTL.get();
            if (formatter == null) {
                formatter = new SimpleDateFormat(pattern);
                formatterTL.set(formatter);
            }
            tsValue = formatter.format(new Date(ts));
        }
    }
    return tsValue;
}

From source file:com.espertech.esper.core.service.EPRuntimeIsolatedImpl.java

private void initThreadLocals() {
    matchesPerStmtThreadLocal = new ThreadLocal<Map<EPStatementAgentInstanceHandle, ArrayDeque<FilterHandleCallback>>>() {
        protected synchronized Map<EPStatementAgentInstanceHandle, ArrayDeque<FilterHandleCallback>> initialValue() {
            if (isPrioritized) {
                return new TreeMap<EPStatementAgentInstanceHandle, ArrayDeque<FilterHandleCallback>>(
                        EPStatementAgentInstanceHandleComparator.INSTANCE);
            } else {
                return new HashMap<EPStatementAgentInstanceHandle, ArrayDeque<FilterHandleCallback>>();
            }/* w  w w .  ja  va 2  s  .  c o  m*/
        }
    };

    schedulePerStmtThreadLocal = new ThreadLocal<Map<EPStatementAgentInstanceHandle, Object>>() {
        protected synchronized Map<EPStatementAgentInstanceHandle, Object> initialValue() {
            if (isPrioritized) {
                return new TreeMap<EPStatementAgentInstanceHandle, Object>(
                        EPStatementAgentInstanceHandleComparator.INSTANCE);
            } else {
                return new HashMap<EPStatementAgentInstanceHandle, Object>();
            }
        }
    };

    matchesArrayThreadLocal = new ThreadLocal<ArrayBackedCollection<FilterHandle>>() {
        protected synchronized ArrayBackedCollection<FilterHandle> initialValue() {
            return new ArrayBackedCollection<FilterHandle>(100);
        }
    };

    scheduleArrayThreadLocal = new ThreadLocal<ArrayBackedCollection<ScheduleHandle>>() {
        protected synchronized ArrayBackedCollection<ScheduleHandle> initialValue() {
            return new ArrayBackedCollection<ScheduleHandle>(100);
        }
    };
}