Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
After reading Hidden Features of C# I wondered, What are some of the hidden features of Java?
When should I use a ThreadLocal variable? How is it used?
I noticed some confusion initially with my question. I'm not asking about how to configure a logger nor how to use a logger properly, but rather how to capture all of the information that would have been logged at a lower logging level than what the current logging level is in the exception message. I have been noticing two patterns in Java for logging information that may be useful to a devel...
This question led me to wonder about thread-local storage in high-level development frameworks like Java and .NET. Java has a ThreadLocal<T> class (and perhaps other constructs), while .NET has data slots, and soon a ThreadLocal<T> class of its own. (It also has the ThreadStaticAttribute, but I'm particularly interested in thread-local storage for member data.) Most other modern de...
What's the best practice? A single session for the whole app A session per window A session per thread, and detaching everything at random Something else? I've googled around, and there's no consensus. Everyone says something, and then takes it back. I find lugging a session around stupid... So, what's the deal?
What is the typical use of ThreadLocal in java. When does one use it? I couldn't application details from this java docs article.
I'm building a JSF+Facelets web app, one piece of which is a method that scans a directory every so often and indexes any changes. This method is part of a bean which is in application scope. I have built a subclass of TimerTask to call the method every X milliseconds. My problem is getting the bean initialized. I can reference the bean on a page, and when I go to the page, the bean is init...
I have a stateless bean with bean-managed transaction and a method like this: @Stateless @TransactionManagement(TransactionManagementType.BEAN) public class ... { @Resource private UserTransaction ut; @EJB private OtherStatelessBeanLocal other; public void invokeSomeMethods() ut.begin(); ... // invoke other bean's methods here. other.me...
I've been using Java for a year or so now, and I constantly find myself discovering new things in the language. Most of this cool stuff, interestingly enough, doesn't come from 3rd-party APIs or libraries, but rather from the classes that ship in the JDK. So I'm wondering, partly out of curiosity and partly for the education of others and myself, what classes that come in the JDK are the most ...
I've started to write some new JBoss timed service that was meant to use some existing seam components. But it seems that I can't access these components because of non-existing contexts. Is it possible to use them other than in the typical situation with JSF? A little snippet to demonstrate what I want to do... @Service public class MyService extends DefaultTimedService implements TimedObjec...
Possible duplicate: When and how should I use a Threadlocal variable The purpose of ThreadLocal as given here states that the variable is local to any Thread accessing an object containing the ThreadLocal variable. What difference does it make, in having a ThreadLocal variable as a member of a class and then making it local to a Thread, rather than having a local variable to the Thread itself?
In Java 1.4, is there any better way of getting a Thread's ID than using Thread.getName()? I mean, getName() in unit tests returns something like "Thread-1", but in WebLogic 10 I get "[ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'.xml".
I was reading that JavaDoc for Threadlocal here http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ThreadLocal.html and it says "ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID). " But my question is why did they choose to make it static (typically) - it makes it a bit confusing to have "per thr...
My limited understanding of ThreadLocal is that it has resource leak issues. I gather this problem can be remedied through proper use of WeakReferences with ThreadLocal (although I may have misunderstood this point.) I would simply like a pattern or example for correctly using ThreadLocal with WeakReference, if one exists. For instance, in this code snippet where would the WeakReference be int...
We know that the dateformat classes are not thread safe. I have a multi-threaded scenario where dateformats needs to be used. I can't really create a new instance in new thread as SimpledateFormat creation seems to be expensive(the constructor ends up calling "compile" which is costly). After some tests the only two options left for me are: External Synchronization - I really dont want to do...
I'm working on an application that consists of an overall Quartz-based scheduler and "CycledJob" run using CronTriggers. The purpose of the application is to process inputs from different email inboxes based on the source country. Based on the country that it comes in from (i.e. US, UK, FR, etc.) the application triggers one job thread to run each country's processing cycle, so there would be...
I have a layered application in Java which has a multi thread data access layer which is invoked from different points. A single call to this layer is likely to spawn several threads to parallelize requests to the DB. What I'm looking for is a logging tool that would allow me to define "activities" that are composed by various threads. Therefore, the same method in the data access layer shoul...
I've downloaded the supposedly latest JDK 1.3 compatible binary named json-lib-2.4-jdk13.jar and am getting the following error. Exception in thread "main" java.lang.NoSuchMethodError: java.lang.ThreadLocal: method remove()V not found at net.sf.json.AbstractJSON.removeInstance(AbstractJSON.java:221) I checked the JDK 1.4 API and noticed that remove method on a ThreadLocal is indeed unsup...
Using threads, I have a principal class (SlaveCrawler) that instantiates three classes(Downloader, ContentAnalyzer, URLAnalyzer) that are dependent on each other. SlaveCrawler uses Downloader and URLAnalyzer Downloader uses ContentAnalyzer and URLAnalyzer ContentAnalyzer uses URLAnalyzer I want only one instance of each class. If I use Singleton, I can get this, but working with threads, I ...
Given that a static variable of a class takes only one memory location, is it shared by all threads of process? Or is one memory location for such a variable created for each of the running threads? Also, if all threads share the same memory location, how can we ensure mutual exclusion?
Hey guys, this is probably a very beginner level question. But I need to get hold of the request object in Java code. I can't pass this object down to my code for certain reasons. Is there any way I can say something like: getCurrentHTTPServletRequest? It is safe for me to assume that I am in a Servlet Context.
  /*
   * Copyright 1997-2007 Sun Microsystems, Inc.  All Rights Reserved.
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   *
   * This code is free software; you can redistribute it and/or modify it
   * under the terms of the GNU General Public License version 2 only, as
   * published by the Free Software Foundation.  Sun designates this
   * particular file as subject to the "Classpath" exception as provided
   * by Sun in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  * version 2 for more details (a copy is included in the LICENSE file that
  * accompanied this code).
  *
  * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  * CA 95054 USA or visit www.sun.com if you need additional information or
  * have any questions.
  */
 
 package java.lang;
This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

For example, the class below generates unique identifiers local to each thread. A thread's id is assigned the first time it invokes ThreadId.get() and remains unchanged on subsequent calls.

 import java.util.concurrent.atomic.AtomicInteger;

 public class ThreadId {
     // Atomic integer containing the next thread ID to be assigned
     private static final AtomicInteger nextId = new AtomicInteger(0);

     // Thread local variable containing each thread's ID
     private static final ThreadLocal<Integer> threadId =
         new ThreadLocal<Integer>() {
             @Override protected Integer initialValue() {
                 return nextId.getAndIncrement();
         }
     };

     // Returns the current thread's unique ID, assigning it if necessary
     public static int get() {
         return threadId.get();
     }
 }
 

Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

Author(s):
Josh Bloch and Doug Lea
Since:
1.2
 
 public class ThreadLocal<T> {
    
ThreadLocals rely on per-thread linear-probe hash maps attached to each thread (Thread.threadLocals and inheritableThreadLocals). The ThreadLocal objects act as keys, searched via threadLocalHashCode. This is a custom hash code (useful only within ThreadLocalMaps) that eliminates collisions in the common case where consecutively constructed ThreadLocals are used by the same threads, while remaining well-behaved in less common cases.
 
     private final int threadLocalHashCode = nextHashCode();

    
The next hash code to be given out. Updated atomically. Starts at zero.
 
     private static AtomicInteger nextHashCode =
         new AtomicInteger();

    
The difference between successively generated hash codes - turns implicit sequential thread-local IDs into near-optimally spread multiplicative hash values for power-of-two-sized tables.
 
     private static final int HASH_INCREMENT = 0x61c88647;

    
Returns the next hash code.
    private static int nextHashCode() {
        return .getAndAdd();
    }

    
Returns the current thread's "initial value" for this thread-local variable. This method will be invoked the first time a thread accesses the variable with the get() method, unless the thread previously invoked the set(java.lang.Object) method, in which case the initialValue method will not be invoked for the thread. Normally, this method is invoked at most once per thread, but it may be invoked again in case of subsequent invocations of remove() followed by get().

This implementation simply returns null; if the programmer desires thread-local variables to have an initial value other than null, ThreadLocal must be subclassed, and this method overridden. Typically, an anonymous inner class will be used.

Returns:
the initial value for this thread-local
    protected T initialValue() {
        return null;
    }

    
Creates a thread local variable.
    public ThreadLocal() {
    }

    
Returns the value in the current thread's copy of this thread-local variable. If the variable has no value for the current thread, it is first initialized to the value returned by an invocation of the initialValue() method.

Returns:
the current thread's value of this thread-local
    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null)
                return (T)e.value;
        }
        return setInitialValue();
    }

    
Variant of set() to establish initialValue. Used instead of set() in case user has overridden the set() method.

Returns:
the initial value
    private T setInitialValue() {
        T value = initialValue();
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(thisvalue);
        else
            createMap(tvalue);
        return value;
    }

    
Sets the current thread's copy of this thread-local variable to the specified value. Most subclasses will have no need to override this method, relying solely on the initialValue() method to set the values of thread-locals.

Parameters:
value the value to be stored in the current thread's copy of this thread-local.
    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(thisvalue);
        else
            createMap(tvalue);
    }

    
Removes the current thread's value for this thread-local variable. If this thread-local variable is subsequently read by the current thread, its value will be reinitialized by invoking its initialValue() method, unless its value is set by the current thread in the interim. This may result in multiple invocations of the initialValue method in the current thread.

Since:
1.5
     public void remove() {
         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
             m.remove(this);
     }

    
Get the map associated with a ThreadLocal. Overridden in InheritableThreadLocal.

Parameters:
t the current thread
Returns:
the map
        return t.threadLocals;
    }

    
Create the map associated with a ThreadLocal. Overridden in InheritableThreadLocal.

Parameters:
t the current thread
firstValue value for the initial entry of the map
map the map to store.
    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(thisfirstValue);
    }

    
Factory method to create map of inherited thread locals. Designed to be called only from Thread constructor.

Parameters:
parentMap the map associated with parent thread
Returns:
a map containing the parent's inheritable bindings
    static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
        return new ThreadLocalMap(parentMap);
    }

    
Method childValue is visibly defined in subclass InheritableThreadLocal, but is internally defined here for the sake of providing createInheritedMap factory method without needing to subclass the map class in InheritableThreadLocal. This technique is preferable to the alternative of embedding instanceof tests in methods.
    T childValue(T parentValue) {
        throw new UnsupportedOperationException();
    }

    
ThreadLocalMap is a customized hash map suitable only for maintaining thread local values. No operations are exported outside of the ThreadLocal class. The class is package private to allow declaration of fields in class Thread. To help deal with very large and long-lived usages, the hash table entries use WeakReferences for keys. However, since reference queues are not used, stale entries are guaranteed to be removed only when the table starts running out of space.
    static class ThreadLocalMap {

        
The entries in this hash map extend WeakReference, using its main ref field as the key (which is always a ThreadLocal object). Note that null keys (i.e. entry.get() == null) mean that the key is no longer referenced, so the entry can be expunged from table. Such entries are referred to as "stale entries" in the code that follows.
        static class Entry extends WeakReference<ThreadLocal> {
            
The value associated with this ThreadLocal.
            Object value;
            Entry(ThreadLocal kObject v) {
                super(k);
                 = v;
            }
        }

        
The initial capacity -- MUST be a power of two.
        private static final int INITIAL_CAPACITY = 16;

        
The table, resized as necessary. table.length MUST always be a power of two.
        private Entry[] table;

        
The number of entries in the table.
        private int size = 0;

        
The next size value at which to resize.
        private int threshold// Default to 0

        
Set the resize threshold to maintain at worst a 2/3 load factor.
        private void setThreshold(int len) {
             = len * 2 / 3;
        }

        
Increment i modulo len.
        private static int nextIndex(int iint len) {
            return ((i + 1 < len) ? i + 1 : 0);
        }

        
Decrement i modulo len.
        private static int prevIndex(int iint len) {
            return ((i - 1 >= 0) ? i - 1 : len - 1);
        }

        
Construct a new map initially containing (firstKey, firstValue). ThreadLocalMaps are constructed lazily, so we only create one when we have at least one entry to put in it.
        ThreadLocalMap(ThreadLocal firstKeyObject firstValue) {
             = new Entry[];
            int i = firstKey.threadLocalHashCode & ( - 1);
            [i] = new Entry(firstKeyfirstValue);
             = 1;
            setThreshold();
        }

        
Construct a new map including all Inheritable ThreadLocals from given parent map. Called only by createInheritedMap.

Parameters:
parentMap the map associated with parent thread.
        private ThreadLocalMap(ThreadLocalMap parentMap) {
            Entry[] parentTable = parentMap.table;
            int len = parentTable.length;
            setThreshold(len);
             = new Entry[len];
            for (int j = 0; j < lenj++) {
                Entry e = parentTable[j];
                if (e != null) {
                    ThreadLocal key = e.get();
                    if (key != null) {
                        Object value = key.childValue(e.value);
                        Entry c = new Entry(keyvalue);
                        int h = key.threadLocalHashCode & (len - 1);
                        while ([h] != null)
                            h = nextIndex(hlen);
                        [h] = c;
                        ++;
                    }
                }
            }
        }

        
Get the entry associated with key. This method itself handles only the fast path: a direct hit of existing key. It otherwise relays to getEntryAfterMiss. This is designed to maximize performance for direct hits, in part by making this method readily inlinable.

Parameters:
key the thread local object
Returns:
the entry associated with key, or null if no such
        private Entry getEntry(ThreadLocal key) {
            int i = key.threadLocalHashCode & (. - 1);
            Entry e = [i];
            if (e != null && e.get() == key)
                return e;
            else
                return getEntryAfterMiss(keyie);
        }

        
Version of getEntry method for use when key is not found in its direct hash slot.

Parameters:
key the thread local object
i the table index for key's hash code
e the entry at table[i]
Returns:
the entry associated with key, or null if no such
        private Entry getEntryAfterMiss(ThreadLocal keyint iEntry e) {
            Entry[] tab = ;
            int len = tab.length;
            while (e != null) {
                ThreadLocal k = e.get();
                if (k == key)
                    return e;
                if (k == null)
                    expungeStaleEntry(i);
                else
                    i = nextIndex(ilen);
                e = tab[i];
            }
            return null;
        }

        
Set the value associated with key.

Parameters:
key the thread local object
value the value to be set
        private void set(ThreadLocal keyObject value) {
            // We don't use a fast path as with get() because it is at
            // least as common to use set() to create new entries as
            // it is to replace existing ones, in which case, a fast
            // path would fail more often than not.
            Entry[] tab = ;
            int len = tab.length;
            int i = key.threadLocalHashCode & (len-1);
            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(ilen)]) {
                ThreadLocal k = e.get();
                if (k == key) {
                    e.value = value;
                    return;
                }
                if (k == null) {
                    replaceStaleEntry(keyvaluei);
                    return;
                }
            }
            tab[i] = new Entry(keyvalue);
            int sz = ++;
            if (!cleanSomeSlots(isz) && sz >= )
                rehash();
        }

        
Remove the entry for key.
        private void remove(ThreadLocal key) {
            Entry[] tab = ;
            int len = tab.length;
            int i = key.threadLocalHashCode & (len-1);
            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(ilen)]) {
                if (e.get() == key) {
                    e.clear();
                    expungeStaleEntry(i);
                    return;
                }
            }
        }

        
Replace a stale entry encountered during a set operation with an entry for the specified key. The value passed in the value parameter is stored in the entry, whether or not an entry already exists for the specified key. As a side effect, this method expunges all stale entries in the "run" containing the stale entry. (A run is a sequence of entries between two null slots.)

Parameters:
key the key
value the value to be associated with key
staleSlot index of the first stale entry encountered while searching for key.
        private void replaceStaleEntry(ThreadLocal keyObject value,
                                       int staleSlot) {
            Entry[] tab = ;
            int len = tab.length;
            Entry e;
            // Back up to check for prior stale entry in current run.
            // We clean out whole runs at a time to avoid continual
            // incremental rehashing due to garbage collector freeing
            // up refs in bunches (i.e., whenever the collector runs).
            int slotToExpunge = staleSlot;
            for (int i = prevIndex(staleSlotlen);
                 (e = tab[i]) != null;
                 i = prevIndex(ilen))
                if (e.get() == null)
                    slotToExpunge = i;
            // Find either the key or trailing null slot of run, whichever
            // occurs first
            for (int i = nextIndex(staleSlotlen);
                 (e = tab[i]) != null;
                 i = nextIndex(ilen)) {
                ThreadLocal k = e.get();
                // If we find key, then we need to swap it
                // with the stale entry to maintain hash table order.
                // The newly stale slot, or any other stale slot
                // encountered above it, can then be sent to expungeStaleEntry
                // to remove or rehash all of the other entries in run.
                if (k == key) {
                    e.value = value;
                    tab[i] = tab[staleSlot];
                    tab[staleSlot] = e;
                    // Start expunge at preceding stale entry if it exists
                    if (slotToExpunge == staleSlot)
                        slotToExpunge = i;
                    cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
                    return;
                }
                // If we didn't find stale entry on backward scan, the
                // first stale entry seen while scanning for key is the
                // first still present in the run.
                if (k == null && slotToExpunge == staleSlot)
                    slotToExpunge = i;
            }
            // If key not found, put new entry in stale slot
            tab[staleSlot]. = null;
            tab[staleSlot] = new Entry(keyvalue);
            // If there are any other stale entries in run, expunge them
            if (slotToExpunge != staleSlot)
                cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
        }

        
Expunge a stale entry by rehashing any possibly colliding entries lying between staleSlot and the next null slot. This also expunges any other stale entries encountered before the trailing null. See Knuth, Section 6.4

Parameters:
staleSlot index of slot known to have null key
Returns:
the index of the next null slot after staleSlot (all between staleSlot and this slot will have been checked for expunging).
        private int expungeStaleEntry(int staleSlot) {
            Entry[] tab = ;
            int len = tab.length;
            // expunge entry at staleSlot
            tab[staleSlot]. = null;
            tab[staleSlot] = null;
            --;
            // Rehash until we encounter null
            Entry e;
            int i;
            for (i = nextIndex(staleSlotlen);
                 (e = tab[i]) != null;
                 i = nextIndex(ilen)) {
                ThreadLocal k = e.get();
                if (k == null) {
                    e.value = null;
                    tab[i] = null;
                    --;
                } else {
                    int h = k.threadLocalHashCode & (len - 1);
                    if (h != i) {
                        tab[i] = null;
                        // Unlike Knuth 6.4 Algorithm R, we must scan until
                        // null because multiple entries could have been stale.
                        while (tab[h] != null)
                            h = nextIndex(hlen);
                        tab[h] = e;
                    }
                }
            }
            return i;
        }

        
Heuristically scan some cells looking for stale entries. This is invoked when either a new element is added, or another stale one has been expunged. It performs a logarithmic number of scans, as a balance between no scanning (fast but retains garbage) and a number of scans proportional to number of elements, that would find all garbage but would cause some insertions to take O(n) time.

Parameters:
i a position known NOT to hold a stale entry. The scan starts at the element after i.
n scan control: log2(n) cells are scanned, unless a stale entry is found, in which case log2(table.length)-1 additional cells are scanned. When called from insertions, this parameter is the number of elements, but when from replaceStaleEntry, it is the table length. (Note: all this could be changed to be either more or less aggressive by weighting n instead of just using straight log n. But this version is simple, fast, and seems to work well.)
Returns:
true if any stale entries have been removed.
        private boolean cleanSomeSlots(int iint n) {
            boolean removed = false;
            Entry[] tab = ;
            int len = tab.length;
            do {
                i = nextIndex(ilen);
                Entry e = tab[i];
                if (e != null && e.get() == null) {
                    n = len;
                    removed = true;
                    i = expungeStaleEntry(i);
                }
            } while ( (n >>>= 1) != 0);
            return removed;
        }

        
Re-pack and/or re-size the table. First scan the entire table removing stale entries. If this doesn't sufficiently shrink the size of the table, double the table size.
        private void rehash() {
            expungeStaleEntries();
            // Use lower threshold for doubling to avoid hysteresis
            if ( >=  -  / 4)
                resize();
        }

        
Double the capacity of the table.
        private void resize() {
            Entry[] oldTab = ;
            int oldLen = oldTab.length;
            int newLen = oldLen * 2;
            Entry[] newTab = new Entry[newLen];
            int count = 0;
            for (int j = 0; j < oldLen; ++j) {
                Entry e = oldTab[j];
                if (e != null) {
                    ThreadLocal k = e.get();
                    if (k == null) {
                        e.value = null// Help the GC
                    } else {
                        int h = k.threadLocalHashCode & (newLen - 1);
                        while (newTab[h] != null)
                            h = nextIndex(hnewLen);
                        newTab[h] = e;
                        count++;
                    }
                }
            }
            setThreshold(newLen);
             = count;
             = newTab;
        }

        
Expunge all stale entries in the table.
        private void expungeStaleEntries() {
            Entry[] tab = ;
            int len = tab.length;
            for (int j = 0; j < lenj++) {
                Entry e = tab[j];
                if (e != null && e.get() == null)
                    expungeStaleEntry(j);
            }
        }
    }
New to GrepCode? Check out our FAQ X