From: Olaf Klischat on
On 07/19/2010 10:40 PM, Daniel Pitts wrote:
> On 7/19/2010 1:37 PM, Daniel Pitts wrote:
>> On 7/19/2010 11:39 AM, markspace wrote:
>>> So here's another thread safety question: is the
>>> JTextArea.append(String) really thread safe? Here's the guts of the
>>> method in question:
>>>
>>> public void append(String str) {
>>> Document doc = getDocument();
>>> if (doc != null) {
>>> try {
>>> doc.insertString(doc.getLength(), str, null);
>>> } catch (BadLocationException e) {
>>> }
>>> }
>>> }
>> The Document object itself is thread-safe, at least with regards to
>> insertString see:
>> <http://download.oracle.com/docs/cd/E17476_01/javase/1.4.2/docs/api/javax/swing/text/Document.html#insertString%28int,%20java.lang.String,%20javax.swing.text.AttributeSet%29>
>>
> Sorry, wrong javadoc...
> The AbstractDocument class javadoc states that the method is thread safe.
> <http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/javax/swing/text/AbstractDocument.html#insertString%28int,%20java.lang.String,%20javax.swing.text.AttributeSet%29>

Well, technically, somebody could write a separate implementation of
Document without extending AbstractDocument, so the thread-safety should
be part of the interface's contract. More importantly, the two calls on
the document in

doc.insertString(doc.getLength(), str, null);

....aren't synchronized, so I suppose it might happen that the index
returned by getLength() no longer points to the end of the document by
the time insertString() is called, resulting in either a
BadLocationException (which is eaten and results in the append()
operation doing nothing) or an insertion of the string before the end of
the document -- both cases seem to violate the contract of the append()
method.