PageRenderTime 42ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/bundles/plugins-trunk/CommonControls/common/threads/WorkRequest.java

#
Java | 101 lines | 54 code | 11 blank | 36 comment | 2 complexity | 18b4b72b27273f68857d1361a7eee9d4 MD5 | raw file
Possible License(s): BSD-3-Clause, AGPL-1.0, Apache-2.0, LGPL-2.0, LGPL-3.0, GPL-2.0, CC-BY-SA-3.0, LGPL-2.1, GPL-3.0, MPL-2.0-no-copyleft-exception, IPL-1.0
  1. /*
  2. * WorkRequest.java - a work request in a WorkThreadPool.
  3. * Copyright (c) 2005 Marcelo Vanzin
  4. *
  5. * :tabSize=4:indentSize=4:noTabs=false:maxLineLen=0:
  6. *
  7. * This program is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU General Public License
  9. * as published by the Free Software Foundation; either version 2
  10. * of the License, or any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  20. */
  21. package common.threads;
  22. import org.gjt.sp.util.Log;
  23. /**
  24. * <p>A work request to the thread pool. Allow other threads to wait until
  25. * the "runnable" is finished. This is basically a concurrent.Future implementation.
  26. *
  27. * @see java.util.concurrent.Future
  28. * @see org.gjt.sp.util.Task
  29. * @see org.gjt.sp.util.ThreadUtilities
  30. * @author Marcelo Vanzin
  31. * @since CC 0.9.0
  32. */
  33. public final class WorkRequest
  34. {
  35. private volatile boolean done;
  36. private Object lock;
  37. private Runnable work;
  38. private Exception error;
  39. public WorkRequest(Runnable work)
  40. {
  41. this.done = false;
  42. this.lock = new Object();
  43. this.work = work;
  44. }
  45. /** Waits until the running job is finished. */
  46. public void waitFor() throws InterruptedException
  47. {
  48. if (done)
  49. return;
  50. synchronized (lock)
  51. {
  52. while (!done) {
  53. lock.wait(1000);
  54. }
  55. }
  56. }
  57. public boolean isDone() {
  58. synchronized (lock)
  59. {
  60. return done;
  61. }
  62. }
  63. /**
  64. * Returns any exception that was caught while running the request.
  65. *
  66. * @since CC 0.9.4
  67. */
  68. public Exception getError()
  69. {
  70. return error;
  71. }
  72. protected void run()
  73. {
  74. try {
  75. work.run();
  76. } catch (Exception e) {
  77. Log.log(Log.ERROR, this, e);
  78. error = e;
  79. }
  80. synchronized (lock)
  81. {
  82. done = true;
  83. lock.notifyAll();
  84. }
  85. }
  86. protected Runnable getRunnable()
  87. {
  88. return work;
  89. }
  90. }