Example usage for java.lang ThreadLocal set

List of usage examples for java.lang ThreadLocal set

Introduction

In this page you can find the example usage for java.lang ThreadLocal set.

Prototype

public void set(T value) 

Source Link

Document

Sets the current thread's copy of this thread-local variable to the specified value.

Usage

From source file:Main.java

public static void main(String[] args) {
    ThreadLocal<Integer> tlocal = new ThreadLocal<Integer>();
    tlocal.set(100);

    System.out.println("value = " + tlocal.get());
}

From source file:Main.java

public static void main(String[] args) {

    ThreadLocal<Integer> tlocal = new ThreadLocal<Integer>();

    tlocal.set(100);
    // returns the current thread's value
    System.out.println("value = " + tlocal.get());

}

From source file:Main.java

public static void main(String[] args) {

    ThreadLocal<Integer> tlocal = new ThreadLocal<Integer>();

    tlocal.set(50);
    System.out.println("value = " + tlocal.get());

    tlocal.remove();/*from w w w.  j  a  v a  2  s . c  o m*/
    System.out.println("value = " + tlocal.get());
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    ThreadLocal localThread = new ThreadLocal();
    Object o = localThread.get();
    localThread.set(o);

}

From source file:Main.java

public static <T> void remove(ThreadLocal<T> threadLocal) {
    threadLocal.set(null);
    threadLocal.remove();
}

From source file:Main.java

public synchronized static void put(String key, Object value) {
    ThreadLocal tl = (ThreadLocal) THREAD_LOCAL_MAP.get(key);
    if (tl == null) {
        tl = new ThreadLocal();
        THREAD_LOCAL_MAP.put(key, tl);/*from w w  w .ja  v  a 2s.  co  m*/
    }
    tl.set(value);
}

From source file:Main.java

public synchronized static void append(String key, String msg) {
    ThreadLocal tl = (ThreadLocal) THREAD_LOCAL_MAP.get(key);
    if (tl == null) {
        tl = new ThreadLocal();
        THREAD_LOCAL_MAP.put(key, tl);/*from   w w  w .ja  va  2  s .  co  m*/
    }
    StringBuffer buf = (StringBuffer) tl.get();
    if (buf == null) {
        buf = new StringBuffer();
        tl.set(buf);
    }
    buf.append(msg).append("\n");
}

From source file:com.strategicgains.docussandra.controller.perf.remote.mongo.MongoLoader.java

public static void loadMongoData(MongoClientURI uri, final int NUM_WORKERS, Database database,
        final int numDocs, final PerfTestParent clazz) {
    logger.info("------------Loading Data into: " + database.name() + " with MONGO!------------");
    try {// w w  w .  j ava  2s  .c o  m
        try {
            MongoClient mongoClient = new MongoClient(uri);
            mongoClient.setWriteConcern(WriteConcern.MAJORITY);
            DB db = mongoClient.getDB(database.name());
            final DBCollection coll = db.getCollection(database.name());
            ArrayList<Thread> workers = new ArrayList<>(NUM_WORKERS + 1);
            int docsPerWorker = numDocs / NUM_WORKERS;
            try {
                List<Document> docs = clazz.getDocumentsFromFS();
                ArrayList<List<Document>> documentQueues = new ArrayList<>(NUM_WORKERS + 1);
                int numDocsAssigned = 0;
                while ((numDocsAssigned + 1) < numDocs) {
                    int start = numDocsAssigned;
                    int end = numDocsAssigned + docsPerWorker;
                    if (end > numDocs) {
                        end = numDocs - 1;
                    }
                    documentQueues.add(new ArrayList(docs.subList(start, end)));
                    numDocsAssigned = end;
                }
                for (final List<Document> queue : documentQueues) {
                    workers.add(new Thread() {
                        @Override
                        public void run() {
                            for (Document d : queue) {
                                DBObject o = (DBObject) JSON.parse(d.object());
                                coll.save(o);
                            }
                            logger.info("Thread " + Thread.currentThread().getName() + " is done. It processed "
                                    + queue.size() + " documents.");
                        }
                    });
                }
            } catch (UnsupportedOperationException e)//we can't read everything in at once
            {
                //all we need to do in this block is find a way to set "workers"
                for (int i = 0; i < NUM_WORKERS; i++) {
                    workers.add(new Thread() {
                        private final int chunk = (int) (Math.random() * 100) + 150;//pick a random chunk so we are not going back to the FS all at the same time and potentially causing a bottle neck

                        @Override
                        public void run() {
                            ThreadLocal<Integer> counter = new ThreadLocal<>();
                            counter.set(new Integer(0));
                            try {
                                List<Document> docs = clazz.getDocumentsFromFS(chunk);//grab a handful of documents
                                while (docs.size() > 0) {
                                    for (Document d : docs)//process the documents we grabbed
                                    {
                                        DBObject o = (DBObject) JSON.parse(d.object());
                                        coll.save(o);
                                        counter.set(counter.get() + 1);
                                    }
                                    docs = clazz.getDocumentsFromFS(chunk);//grab another handful of documents
                                }
                                logger.info("Thread " + Thread.currentThread().getName()
                                        + " is done. It processed " + counter.get() + " documents.");
                            } catch (IOException | ParseException e) {
                                logger.error("Couldn't read from document", e);
                            }
                        }
                    });
                }
            }

            long start = new Date().getTime();
            //start your threads!
            for (Thread t : workers) {
                t.start();
            }
            logger.info("All threads started, waiting for completion.");
            boolean allDone = false;
            boolean first = true;
            while (!allDone || first) {
                first = false;
                boolean done = true;
                for (Thread t : workers) {
                    if (t.isAlive()) {
                        done = false;
                        logger.info("Thread " + t.getName() + " is still running.");
                        break;
                    }
                }
                if (done) {
                    allDone = true;
                } else {
                    logger.info("We still have workers running...");
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                    }
                }
            }
            long end = new Date().getTime();
            long miliseconds = end - start;
            double seconds = (double) miliseconds / 1000d;
            output.info("Done loading data using: " + NUM_WORKERS + ". Took: " + seconds + " seconds");
            double tpms = (double) numDocs / (double) miliseconds;
            double tps = tpms * 1000;
            double transactionTime = (double) miliseconds / (double) numDocs;
            output.info(database.name() + " Mongo Average Transactions Per Second: " + tps);
            output.info(
                    database.name() + " Mongo Average Transactions Time (in miliseconds): " + transactionTime);

        } catch (UnknownHostException e) {
            logger.error("Couldn't connect to Mongo Server", e);
        }
    } catch (IOException | ParseException e) {
        logger.error("Couldn't read data.", e);
    }
}

From source file:org.apache.sysml.runtime.matrix.data.LibMatrixNative.java

private static FloatBuffer toFloatBuffer(double[] input, ThreadLocal<FloatBuffer> buff, boolean copy) {
    //maintain thread-local buffer (resized on demand)
    FloatBuffer ret = buff.get();
    if (ret == null || ret.capacity() < input.length) {
        ret = ByteBuffer.allocateDirect(4 * input.length).order(ByteOrder.nativeOrder()).asFloatBuffer();
        buff.set(ret);
    }//from  w ww  . j ava 2s  .  c  o m
    //copy to direct byte buffer
    final FloatBuffer ret2 = ret;
    if (copy) {
        IntStream.range(0, input.length).parallel().forEach(i -> ret2.put(i, (float) input[i]));
    }
    return ret2;
}

From source file:com.netsteadfast.greenstep.bsc.util.BscReportSupportUtils.java

public static void loadExpression(ThreadLocal<SysExpressionVO> exprThreadLocal, String exprId)
        throws ServiceException, Exception {
    if (exprThreadLocal.get() == null) {
        SysExpressionVO sysExpression = new SysExpressionVO();
        sysExpression.setExprId(exprId);
        DefaultResult<SysExpressionVO> result = sysExpressionService.findByUkCacheable(sysExpression);
        if (result.getValue() != null) {
            sysExpression = result.getValue();
            exprThreadLocal.set(sysExpression);
        }//from   w ww.ja  v a  2 s. c  om
    }
}