1. /*
  2. * @(#)LayoutQueue.java 1.5 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 javax.swing.text;
  8. import java.util.Vector;
  9. /**
  10. * A queue of text layout tasks.
  11. *
  12. * @author Timothy Prinzing
  13. * @version 1.5 01/23/03
  14. * @see AsyncBoxView
  15. * @since 1.3
  16. */
  17. public class LayoutQueue {
  18. Vector tasks;
  19. Thread worker;
  20. static LayoutQueue defaultQueue;
  21. /**
  22. * Construct a layout queue.
  23. */
  24. public LayoutQueue() {
  25. tasks = new Vector();
  26. }
  27. /**
  28. * Fetch the default layout queue.
  29. */
  30. public static LayoutQueue getDefaultQueue() {
  31. if (defaultQueue == null) {
  32. defaultQueue = new LayoutQueue();
  33. }
  34. return defaultQueue;
  35. }
  36. /**
  37. * Set the default layout queue.
  38. *
  39. * @param q the new queue.
  40. */
  41. public static void setDefaultQueue(LayoutQueue q) {
  42. defaultQueue = q;
  43. }
  44. /**
  45. * Add a task that is not needed immediately because
  46. * the results are not believed to be visible.
  47. */
  48. public synchronized void addTask(Runnable task) {
  49. if (worker == null) {
  50. worker = new LayoutThread();
  51. worker.start();
  52. }
  53. tasks.addElement(task);
  54. notifyAll();
  55. }
  56. /**
  57. * Used by the worker thread to get a new task to execute
  58. */
  59. protected synchronized Runnable waitForWork() {
  60. while (tasks.size() == 0) {
  61. try {
  62. wait();
  63. } catch (InterruptedException ie) {
  64. return null;
  65. }
  66. }
  67. Runnable work = (Runnable) tasks.firstElement();
  68. tasks.removeElementAt(0);
  69. return work;
  70. }
  71. /**
  72. * low priority thread to perform layout work forever
  73. */
  74. class LayoutThread extends Thread {
  75. LayoutThread() {
  76. super("text-layout");
  77. setPriority(Thread.MIN_PRIORITY);
  78. }
  79. public void run() {
  80. Runnable work;
  81. do {
  82. work = waitForWork();
  83. if (work != null) {
  84. work.run();
  85. }
  86. } while (work != null);
  87. }
  88. }
  89. }