1. /*
  2. * @(#)SegmentCache.java 1.5 03/12/19
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package javax.swing.text;
  8. import java.util.ArrayList;
  9. import java.util.List;
  10. /**
  11. * SegmentCache caches <code>Segment</code>s to avoid continually creating
  12. * and destroying of <code>Segment</code>s. A common use of this class would
  13. * be:
  14. * <pre>
  15. * Segment segment = segmentCache.getSegment();
  16. * // do something with segment
  17. * ...
  18. * segmentCache.releaseSegment(segment);
  19. * </pre>
  20. *
  21. * @version 1.5 12/19/03
  22. */
  23. class SegmentCache {
  24. /**
  25. * A global cache.
  26. */
  27. private static SegmentCache sharedCache = new SegmentCache();
  28. /**
  29. * A list of the currently unused Segments.
  30. */
  31. private List segments;
  32. /**
  33. * Returns the shared SegmentCache.
  34. */
  35. public static SegmentCache getSharedInstance() {
  36. return sharedCache;
  37. }
  38. /**
  39. * A convenience method to get a Segment from the shared
  40. * <code>SegmentCache</code>.
  41. */
  42. public static Segment getSharedSegment() {
  43. return getSharedInstance().getSegment();
  44. }
  45. /**
  46. * A convenience method to release a Segment to the shared
  47. * <code>SegmentCache</code>.
  48. */
  49. public static void releaseSharedSegment(Segment segment) {
  50. getSharedInstance().releaseSegment(segment);
  51. }
  52. /**
  53. * Creates and returns a SegmentCache.
  54. */
  55. public SegmentCache() {
  56. segments = new ArrayList(11);
  57. }
  58. /**
  59. * Returns a <code>Segment</code>. When done, the <code>Segment</code>
  60. * should be recycled by invoking <code>releaseSegment</code>.
  61. */
  62. public Segment getSegment() {
  63. synchronized(this) {
  64. int size = segments.size();
  65. if (size > 0) {
  66. return (Segment)segments.remove(size - 1);
  67. }
  68. }
  69. return new CachedSegment();
  70. }
  71. /**
  72. * Releases a Segment. You should not use a Segment after you release it,
  73. * and you should NEVER release the same Segment more than once, eg:
  74. * <pre>
  75. * segmentCache.releaseSegment(segment);
  76. * segmentCache.releaseSegment(segment);
  77. * </pre>
  78. * Will likely result in very bad things happening!
  79. */
  80. public void releaseSegment(Segment segment) {
  81. if (segment instanceof CachedSegment) {
  82. synchronized(this) {
  83. segment.array = null;
  84. segment.count = 0;
  85. segments.add(segment);
  86. }
  87. }
  88. }
  89. /**
  90. * CachedSegment is used as a tagging interface to determine if
  91. * a Segment can successfully be shared.
  92. */
  93. private static class CachedSegment extends Segment {
  94. }
  95. }