1. /*
  2. * Copyright 2002 Sun Microsystems, Inc. All rights reserved.
  3. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  4. */
  5. package javax.mail;
  6. import java.io.*;
  7. import java.util.Vector;
  8. import javax.mail.event.MailEvent;
  9. /**
  10. * Package private class used by Store & Folder to dispatch events.
  11. * This class implements an event queue, and a dispatcher thread that
  12. * dequeues and dispatches events from the queue.
  13. *
  14. * Pieces stolen from sun.misc.Queue.
  15. *
  16. * @author Bill Shannon
  17. */
  18. class EventQueue implements Runnable {
  19. class QueueElement {
  20. QueueElement next = null;
  21. QueueElement prev = null;
  22. MailEvent event = null;
  23. Vector vector = null;
  24. QueueElement(MailEvent event, Vector vector) {
  25. this.event = event;
  26. this.vector = vector;
  27. }
  28. }
  29. private QueueElement head = null;
  30. private QueueElement tail = null;
  31. private Thread qThread;
  32. public EventQueue() {
  33. qThread = new Thread(this);
  34. qThread.setDaemon(true); // not a user thread
  35. qThread.start();
  36. }
  37. /**
  38. * Enqueue an event.
  39. */
  40. public synchronized void enqueue(MailEvent event, Vector vector) {
  41. QueueElement newElt = new QueueElement(event, vector);
  42. if (head == null) {
  43. head = newElt;
  44. tail = newElt;
  45. } else {
  46. newElt.next = head;
  47. head.prev = newElt;
  48. head = newElt;
  49. }
  50. notify();
  51. }
  52. /**
  53. * Dequeue the oldest object on the queue.
  54. * Used only by the run() method.
  55. *
  56. * @return the oldest object on the queue.
  57. * @exception java.lang.InterruptedException if another thread has
  58. * interrupted this thread.
  59. */
  60. private synchronized QueueElement dequeue()
  61. throws InterruptedException {
  62. while (tail == null)
  63. wait();
  64. QueueElement elt = tail;
  65. tail = elt.prev;
  66. if (tail == null) {
  67. head = null;
  68. } else {
  69. tail.next = null;
  70. }
  71. elt.prev = elt.next = null;
  72. return elt;
  73. }
  74. /**
  75. * Pull events off the queue and dispatch them.
  76. */
  77. public void run() {
  78. QueueElement qe;
  79. try {
  80. while ((qe = dequeue()) != null) {
  81. MailEvent e = qe.event;
  82. Vector v = qe.vector;
  83. for (int i = 0; i < v.size(); i++)
  84. e.dispatch(v.elementAt(i));
  85. qe = null; e = null; v = null;
  86. }
  87. } catch (InterruptedException e) {
  88. // just die
  89. }
  90. }
  91. /**
  92. * Stop the dispatcher so we can be destroyed.
  93. */
  94. void stop() {
  95. if (qThread != null) {
  96. qThread.interrupt(); // kill our thread
  97. qThread = null;
  98. }
  99. }
  100. }