blob: b05b0104d2a16adaf6ddd2a890d6aa63c95ef141 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
|
package org.eclipse.debug.internal.core;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
/**
* Writes to an output stream, queueing output if the
* output stream is blocked.
*/
import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;
public class OutputStreamMonitor {
private final static String PREFIX= "output_stream_monitor.";
private final static String LABEL= PREFIX + "label";
protected OutputStream fStream;
protected Vector fQueue;
protected Thread fThread;
protected Object fLock;
/**
* Creates an output stream monitor on the
* given output stream.
*/
public OutputStreamMonitor(OutputStream stream) {
fStream= stream;
fQueue= new Vector();
fLock= new Object();
}
/**
* Appends the given text to the stream, or
* queues the text to be written at a later time
* if the stream is blocked.
*/
public void write(String text) {
synchronized(fLock) {
fQueue.add(text);
fLock.notifyAll();
}
}
/**
* Starts a <code>Thread</code> which writes the stream.
*/
public void startMonitoring() {
if (fThread == null) {
fThread= new Thread(new Runnable() {
public void run() {
write();
}
}, DebugCoreUtils.getResourceString(LABEL));
fThread.start();
}
}
/**
* Causes the monitor to close all
* communications between it and the
* underlying stream.
*/
public void close() {
if (fThread != null) {
Thread thread= fThread;
fThread= null;
thread.interrupt();
}
}
protected void write() {
while (fThread != null) {
writeNext();
}
}
protected void writeNext() {
while (!fQueue.isEmpty()) {
String text = (String)fQueue.firstElement();
fQueue.removeElementAt(0);
try {
if (fStream != null) {
fStream.write(text.getBytes());
fStream.flush();
}
} catch (IOException e) {
}
}
try {
synchronized(fLock) {
fLock.wait();
}
} catch (InterruptedException e) {
}
}
}
|