1. /*
  2. * @(#)InheritableThreadLocal.java 1.16 03/01/23
  3. *
  4. * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.lang;
  8. import java.lang.ref.*;
  9. /**
  10. * This class extends <tt>ThreadLocal</tt> to provide inheritance of values
  11. * from parent thread to child thread: when a child thread is created, the
  12. * child receives initial values for all inheritable thread-local variables
  13. * for which the parent has values. Normally the child's values will be
  14. * identical to the parent's; however, the child's value can be made an
  15. * arbitrary function of the parent's by overriding the <tt>childValue</tt>
  16. * method in this class.
  17. *
  18. * <p>Inheritable thread-local variables are used in preference to
  19. * ordinary thread-local variables when the per-thread-attribute being
  20. * maintained in the variable (e.g., User ID, Transaction ID) must be
  21. * automatically transmitted to any child threads that are created.
  22. *
  23. * @author Josh Bloch and Doug Lea
  24. * @version 1.16, 01/23/03
  25. * @see ThreadLocal
  26. * @since 1.2
  27. */
  28. public class InheritableThreadLocal extends ThreadLocal {
  29. /**
  30. * Computes the child's initial value for this inheritable thread-local
  31. * variable as a function of the parent's value at the time the child
  32. * thread is created. This method is called from within the parent
  33. * thread before the child is started.
  34. * <p>
  35. * This method merely returns its input argument, and should be overridden
  36. * if a different behavior is desired.
  37. *
  38. * @param parentValue the parent thread's value
  39. * @return the child thread's initial value
  40. */
  41. protected Object childValue(Object parentValue) {
  42. return parentValue;
  43. }
  44. /**
  45. * Get the map associated with a ThreadLocal.
  46. *
  47. * @param t the current thread
  48. */
  49. ThreadLocalMap getMap(Thread t) {
  50. return t.inheritableThreadLocals;
  51. }
  52. /**
  53. * Create the map associated with a ThreadLocal.
  54. *
  55. * @param t the current thread
  56. * @param firstValue value for the initial entry of the table.
  57. * @param map the map to store.
  58. */
  59. void createMap(Thread t, Object firstValue) {
  60. t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
  61. }
  62. }