1. /*
  2. * @(#)CodeSetCache.java 1.8 04/03/01
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package com.sun.corba.se.impl.encoding;
  8. import java.nio.charset.CharsetDecoder;
  9. import java.nio.charset.CharsetEncoder;
  10. import java.util.Map;
  11. import java.util.WeakHashMap;
  12. /**
  13. * Thread local cache of sun.io code set converters for performance.
  14. *
  15. * The thread local class contains a single reference to a Map[]
  16. * containing two WeakHashMaps. One for CharsetEncoders and
  17. * one for CharsetDecoders. Constants are defined for indexing.
  18. *
  19. * This is used internally by CodeSetConversion.
  20. */
  21. class CodeSetCache
  22. {
  23. /**
  24. * The ThreadLocal data is a 2 element Map array indexed
  25. * by BTC_CACHE_MAP and CTB_CACHE_MAP.
  26. */
  27. private ThreadLocal converterCaches = new ThreadLocal() {
  28. public java.lang.Object initialValue() {
  29. return new Map[] { new WeakHashMap(), new WeakHashMap() };
  30. }
  31. };
  32. /**
  33. * Index in the thread local converterCaches array for
  34. * the byte to char converter Map. A key is the Java
  35. * name corresponding to the desired code set.
  36. */
  37. private static final int BTC_CACHE_MAP = 0;
  38. /**
  39. * Index in the thread local converterCaches array for
  40. * the char to byte converter Map. A key is the Java
  41. * name corresponding to the desired code set.
  42. */
  43. private static final int CTB_CACHE_MAP = 1;
  44. /**
  45. * Retrieve a CharsetDecoder from the Map using the given key.
  46. */
  47. CharsetDecoder getByteToCharConverter(Object key) {
  48. Map btcMap = ((Map[])converterCaches.get())[BTC_CACHE_MAP];
  49. return (CharsetDecoder)btcMap.get(key);
  50. }
  51. /**
  52. * Retrieve a CharsetEncoder from the Map using the given key.
  53. */
  54. CharsetEncoder getCharToByteConverter(Object key) {
  55. Map ctbMap = ((Map[])converterCaches.get())[CTB_CACHE_MAP];
  56. return (CharsetEncoder)ctbMap.get(key);
  57. }
  58. /**
  59. * Stores the given CharsetDecoder in the thread local cache,
  60. * and returns the same converter.
  61. */
  62. CharsetDecoder setConverter(Object key, CharsetDecoder converter) {
  63. Map btcMap = ((Map[])converterCaches.get())[BTC_CACHE_MAP];
  64. btcMap.put(key, converter);
  65. return converter;
  66. }
  67. /**
  68. * Stores the given CharsetEncoder in the thread local cache,
  69. * and returns the same converter.
  70. */
  71. CharsetEncoder setConverter(Object key, CharsetEncoder converter) {
  72. Map ctbMap = ((Map[])converterCaches.get())[CTB_CACHE_MAP];
  73. ctbMap.put(key, converter);
  74. return converter;
  75. }
  76. }