Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / GUI / January 2005

Tip: Looking for answers? Try searching our database.

Thread safety tips

Thread view: 
Gyruss - 30 Dec 2004 10:09 GMT
Hi,

I have two SwingWorkers updating a JTextArea simultaneously via the append()
method. What do I need to do to make this operation safe?

Thanks!
Antti S. Brax - 30 Dec 2004 10:27 GMT
gyruss@hushmail.com wrote in comp.lang.java.gui:
> I have two SwingWorkers updating a JTextArea simultaneously via the append()
> method. What do I need to do to make this operation safe?

    Both threads need to have a reference to an object that they use
    as a monitor. Then, they both manipulate the JTextArea in a code
    block that is synchronized by that monitor.

    Since they already share the same JTextArea you might very well be
    able to use it as a monitor:

    synchonized (textArea) {
       textArea.append(...);
    }

Signature

Antti S. Brax                  Rullalautailu pitää lapset poissa ladulta
http://www.iki.fi/asb/         http://www.cs.helsinki.fi/u/abrax/hlb/
       "Disconnect this cable to shorten, re-connect to lengthen."
         -- Instructions on Logitech's USB mouse extension cord.

Antti S. Brax - 30 Dec 2004 10:43 GMT
asb@iki.fi.NO.SPAM wrote in comp.lang.java.gui:
> gyruss@hushmail.com wrote in comp.lang.java.gui:
>> I have two SwingWorkers updating a JTextArea simultaneously via the append()
>> method. What do I need to do to make this operation safe?

    And read this too.

http://java.sun.com/docs/books/tutorial/essential/threads/multithreaded.html

Signature

Antti S. Brax                  Rullalautailu pitää lapset poissa ladulta
http://www.iki.fi/asb/         http://www.cs.helsinki.fi/u/abrax/hlb/
       "Disconnect this cable to shorten, re-connect to lengthen."
         -- Instructions on Logitech's USB mouse extension cord.

John McGrath - 30 Dec 2004 17:04 GMT
> > I have two SwingWorkers updating a JTextArea simultaneously via the
> > append() method. What do I need to do to make this operation safe?
[quoted text clipped - 9 lines]
>        textArea.append(...);
>     }

Actually, that is not necessary.  While almost all Swing components are
not thread-safe and require synchronization, JTextComponent subclasses are
an exception to that rule.  The JTextArea methods that manipulate the
text, including the append() method, *are* thread-safe.

Signature

Regards,

John McGrath

Antti S. Brax - 31 Dec 2004 06:36 GMT
ng@jpmcgrath.net wrote in comp.lang.java.gui:
>> > I have two SwingWorkers updating a JTextArea simultaneously via the
>> > append() method. What do I need to do to make this operation safe?

>>     Since they already share the same JTextArea you might very well be
>>     able to use it as a monitor:

> Actually, that is not necessary.  While almost all Swing components are
> not thread-safe and require synchronization, JTextComponent subclasses are
> an exception to that rule.  The JTextArea methods that manipulate the
> text, including the append() method, *are* thread-safe.

    Now I'm counting the times I've told people the read the API
    first.

    Thanks for the correction. :-)

Signature

Antti S. Brax                  Rullalautailu pitää lapset poissa ladulta
http://www.iki.fi/asb/         http://www.cs.helsinki.fi/u/abrax/hlb/
       "Disconnect this cable to shorten, re-connect to lengthen."
         -- Instructions on Logitech's USB mouse extension cord.

Christian Kaufhold - 31 Dec 2004 19:19 GMT
>> > I have two SwingWorkers updating a JTextArea simultaneously via the
>> > append() method. What do I need to do to make this operation safe?
[quoted text clipped - 14 lines]
> an exception to that rule.  The JTextArea methods that manipulate the
> text, including the append() method, *are* thread-safe.

They are claimed to be thread-safe, but this is not true. In this
specific case, you can call append from *one* thread at the time if you
modify the document only from that thread (e.g. the text area must be
uneditable, or it could be modified from the event-dispatch there and
then cannot be modified also from a background thread), but
not wrong multiple ones (because there is a period without lock between
getLength() and insert() so the insertion position may not be the end
of the document or even invalid).

See articles at http://www.chka.de/swing/text/

Christian
John McGrath - 04 Jan 2005 01:10 GMT
> > While almost all Swing components are not thread-safe and require
> > synchronization, JTextComponent subclasses are an exception to that
> > rule.  The JTextArea methods that manipulate the text, including the
> > append() method, are thread-safe.
>
> They are claimed to be thread-safe, but this is not true.

Very interesting!  Thank you for posting that.

I had noticed the problem with the Document interface - even though most
implementations are thread-safe, the interface it presents requires two
separate operations to add text to the end of the Document, so you have
potential threading problems.  But I assumed that the append() method was
thread-safe, since it is documented to be.  I never really looked past the
documentation.

Checking the Sun Bug Parade, I found a report on this (4765383), but it
was closed as a duplicate of another bug, which was also closed as a
duplicate of a third bug.  The third bug was marked as fixed, although it
does not seem to deal with the same issue.  So it looks to me as if there
is no open bug report on this problem, yet it persists in JDK 1.5.  Have
you submitted a bug report on this?

> See articles at http://www.chka.de/swing/text/

It is interesting that text component methods claim to be thread-safe
based on the assumption that the underlying Document methods will be
thread-safe.  But an interface cannot specify thread-safety, and the
JavaDocs for the Document interface say nothing about thread-safety.

On 12/31/2004 at 1:36:33 AM, Antti S. Brax wrote:

> Now I'm counting the times I've told people the read the API first.

Apparently that is not enough.  They should read the API docs and then not
believe what they say.  :o)

Signature

Regards,

John McGrath

Christian Kaufhold - 04 Jan 2005 14:42 GMT
>> > While almost all Swing components are not thread-safe and require
>> > synchronization, JTextComponent subclasses are an exception to that
[quoted text clipped - 18 lines]
> is no open bug report on this problem, yet it persists in JDK 1.5.  Have
> you submitted a bug report on this?

I tried, but was not understood.


>> See articles at http://www.chka.de/swing/text/
>
> It is interesting that text component methods claim to be thread-safe
> based on the assumption that the underlying Document methods will be
> thread-safe.  But an interface cannot specify thread-safety, and the

Of course it can. Just start the documentation with "Implementations of
Whatever must be thread-safe" (and then define what exactly you mean
by that).

> JavaDocs for the Document interface say nothing about thread-safety.

Eh, "render"? (But it only allows a read lock and thus is useless for
modifications. It also is not supported by the default text component
implementations, instead AbstractDocument's read(Un)lock are used.)

Christian
John McGrath - 05 Jan 2005 08:33 GMT
> > It is interesting that text component methods claim to be thread-safe
> > based on the assumption that the underlying Document methods will be
[quoted text clipped - 3 lines]
> Whatever must be thread-safe" (and then define what exactly you mean
> by that).

We are talking about Java, right?  Java interfaces cannot specify that an
implementation must be thread-safe.  The documentation is not an interface.

> > JavaDocs for the Document interface say nothing about thread-safety.
>
> Eh, "render"?

We were talking about the methods that manipulate the Document's text:
append(), insertString(), etc, and how they are called from JTextArea.

Eh?

Signature

Regards,

John McGrath

Antti S. Brax - 05 Jan 2005 09:27 GMT
ng@jpmcgrath.net wrote in comp.lang.java.gui:

>> > It is interesting that text component methods claim to be thread-safe
>> > based on the assumption that the underlying Document methods will be
[quoted text clipped - 15 lines]
>
> Eh?

    In the beginning we were talking about JTextArea and it's append
    method.

    The JavaDoc for that method says the method is thread safe while
    it in reality is not. It calls getLength and then passes that
    value to insertString without any synchronization. It is clearly
    not threadsafe (this was in 1.4.2).

    Also, the append method eats up the BadLocationException thrown
    by insertString with an empty catch block. So if there is an error
    caused by the method not being thread safe when it's documentation
    claims so, it will also hide the error completely. Good luck
    debugging that...

Signature

Antti S. Brax                  Rullalautailu pitää lapset poissa ladulta
http://www.iki.fi/asb/         http://www.cs.helsinki.fi/u/abrax/hlb/
       "Disconnect this cable to shorten, re-connect to lengthen."
         -- Instructions on Logitech's USB mouse extension cord.

Christian Kaufhold - 07 Jan 2005 16:38 GMT
>> > It is interesting that text component methods claim to be thread-safe
>> > based on the assumption that the underlying Document methods will be
[quoted text clipped - 6 lines]
> We are talking about Java, right?  Java interfaces cannot specify that an
> implementation must be thread-safe.  The documentation is not an interface.

I do not understand what you mean by specify? How can non-abstract methods
specify thread-safety (just making them synchronized does not do anything
except in trivial cases)?


>> > JavaDocs for the Document interface say nothing about thread-safety.
>>
>> Eh, "render"?
>
> We were talking about the methods that manipulate the Document's text:
> append(), insertString(), etc, and how they are called from JTextArea.

Au contraire, you were talking about "JavaDocs for the Document interface"
(see above).

Christian
John McGrath - 07 Jan 2005 23:13 GMT
> > We are talking about Java, right?  Java interfaces cannot specify that
> > an implementation must be thread-safe.  The documentation is not an
> > interface.
>
> I do not understand what you mean by specify? How can non-abstract
> methods specify thread-safety

I do not understand your reference to "non-abstract methods".  The methods
of an interface are *abstract* by definition.

Java interfaces specify the methods that an implementing class must
define, including the types of the arguments they accept, the return type,
and the checked exceptions that the methods may throw.  But there is no
way that they can specify thread safety.

> (just making them synchronized does not do anything except in
> trivial cases)?

Interfaces cannot specify that a method is synchronized.

> > We were talking about the methods that manipulate the Document's text:
> > append(), insertString(), etc, and how they are called from JTextArea.
>
> Au contraire, you were talking about "JavaDocs for the Document
> interface" (see above).

No.  You are taking my statement out of context.  If you will re-read the
thread, you should be able to understand the context.

You seem rather combative.  Is there a reason for this?

Signature

Regards,

John McGrath

Christian Kaufhold - 09 Jan 2005 16:35 GMT
>> > We are talking about Java, right?  Java interfaces cannot specify that
>> > an implementation must be thread-safe.  The documentation is not an
[quoted text clipped - 10 lines]
> and the checked exceptions that the methods may throw.  But there is no
> way that they can specify thread safety.

So how can non-abstract classes (regarding interfaces just as purely
abstract classes) specify thread-safety? How can they do it without
a textual description of how the user of the class is supposed to
use the class's features?

>> trivial cases)?
>
> Interfaces cannot specify that a method is synchronized.

For a non-abstract method, one can make it synchronized. I really wonder
what you mean by "an interface cannot ensure thread-safety" - opposed to
what?


>> > We were talking about the methods that manipulate the Document's text:
>> > append(), insertString(), etc, and how they are called from JTextArea.
[quoted text clipped - 4 lines]
> No.  You are taking my statement out of context.  If you will re-read the
> thread, you should be able to understand the context.

Yes. In the context of calling Document methods (by JTextArea), you were
talking about Document documentation not mentioning thread-safety. I was
merely pointing out that in the documentation for "render", there is some
idea of thread-safety (though of course incomplete).

> You seem rather combative.  Is there a reason for this?

I am angry at myself because I seem to be incapable to make myself understood.

Christian
John McGrath - 10 Jan 2005 10:58 GMT
> So how can non-abstract classes (regarding interfaces just as purely
> abstract classes) specify thread-safety? How can they do it without
> a textual description of how the user of the class is supposed to
> use the class's features?

First, I should say that I do not really think that "specify" is the best
word to use in this context, since a class implementation does not really
*specify* thread-safety.  It either is thread-safe, or it is not.

That said, the answer depends on your definition of the term
"thread-safe".  I have seen numerous definitions put forth by various
people, and while those definitions are similar, the differences are quite
important in this context.

Some would say that a class is thread-safe if its internal state cannot be
left inconsistent through concurrent access.  Others would say that a
class is thread-safe if it can be effectively used concurrently.  I am
sure that others would come up with different definitions.  What is your
definition?

> For a non-abstract method, one can make it synchronized.

Of course.

> I really wonder what you mean by "an interface cannot ensure
> thread-safety"

Actually, the word I used was "specify"; my exact words were "an interface
cannot specify thread-safety".  The meaning seems pretty clear to me, but
I will try to make it more clear:  It is not possible for a Java interface
to specify that an implementing class must be thread-safe.

> - opposed to what?

As opposed to an interface being able to specify thread-safety.

> >> Au contraire, you were talking about "JavaDocs for the Document
> >> interface" (see above).
[quoted text clipped - 3 lines]
>
> Yes. In the context of calling Document methods (by JTextArea),

No, you are missing part of the context.  We were talking about the
methods in the Document interface called by JTextArea methods that are
documented as being thread-safe.

Signature

Regards,

John McGrath

Christian Kaufhold - 11 Jan 2005 17:10 GMT
>> So how can non-abstract classes (regarding interfaces just as purely
>> abstract classes) specify thread-safety? How can they do it without
[quoted text clipped - 4 lines]
> word to use in this context, since a class implementation does not really
> *specify* thread-safety.  It either is thread-safe, or it is not.

But unless that is *stated* somehow (and that is only possible by
documentation in Java), it is irrelevant whether it is or not, since
users of the class cannot rely on it (unless they also have control
over the class implementation itself).

Similarly, just as implementing a class and documenting that it
is thread-safe (by whatever definition), one can require (in the
written specification) that an implementation of a specific interface
(or a subclass of an abstract class) must be thread-safe (by whatever
definition). For a user of that class or subclasses or classes that
implement that interface there is no difference.


> That said, the answer depends on your definition of the term
> "thread-safe".  I have seen numerous definitions put forth by various
> people, and while those definitions are similar, the differences are quite
> important in this context.

I don't think it depends on the definition here (in fact I think my point
does not even depend on the notion of "thread-safety").

> Some would say that a class is thread-safe if its internal state cannot be
> left inconsistent through concurrent access.  Others would say that a
> class is thread-safe if it can be effectively used concurrently.  I am
> sure that others would come up with different definitions.  What is your
> definition?

It depends. Maybe just "there is some well-defined possibility to use
an object of the class by multiple threads". But by that definition,
probably every Java class is thread-safe (by synchronizing on an ex-
ternal lock before any access to its features).


>> - opposed to what?
>
> As opposed to an interface being able to specify thread-safety.

I still don't understand how that is specific to interfaces.

Christian
John McGrath - 12 Jan 2005 01:44 GMT
> > First, I should say that I do not really think that "specify" is the
> > best word to use in this context, since a class implementation does
[quoted text clipped - 5 lines]
> users of the class cannot rely on it (unless they also have control
> over the class implementation itself).

Yes, of course.  That is why I took note that the JavaDocs for the
Document interface do not say anything about thread-safety of the text
modification methods.  JTextArea does claim thread-safety, but the claim
is based on ... nothing at all.

> Similarly, just as implementing a class and documenting that it
> is thread-safe (by whatever definition), one can require (in the
> written specification) that an implementation of a specific interface
> (or a subclass of an abstract class) must be thread-safe (by whatever
> definition). For a user of that class or subclasses or classes that
> implement that interface there is no difference.

Are you saying that there is no difference between specifying
thread-safety in the documentation and specifying it in the class /
interface definition?  If so, I would disagree.  If class or interface
definitions could specify thread-safety. then tools could use this
information.  For example, thread analyzers could point to possible unsafe
uses of the class.  This is not possible with text descriptions of
thread-safety.

Java does not allow any such specification of thread-safety, and I am not
sure if there are any languages that do, or even if we have concepts that
are sufficiently defined to all such a specification.  But assuming that
were possible, I think defining the notion in the code would be very
beneficial.

> > That said, the answer depends on your definition of the term
> > "thread-safe".  I have seen numerous definitions put forth by various
[quoted text clipped - 3 lines]
> I don't think it depends on the definition here (in fact I think my point
> does not even depend on the notion of "thread-safety").

I do not understand your point.  Your question was, "how can non-abstract
classes ... specify thread-safety?"  How can the answer to that not depend
on the definition of thread-safety?

> > Some would say that a class is thread-safe if its internal state
> > cannot be left inconsistent through concurrent access.  Others would
[quoted text clipped - 6 lines]
> probably every Java class is thread-safe (by synchronizing on an ex-
> ternal lock before any access to its features).

That definition was not explicit enough.  Please amend it to include the
phrase "without external synchronization".  Of course, one problem with
adding external synchronization is that it requires that you know every
bit of code that might try to access the class, and that you consistently
apply the synchronization using the same lock.  This is always possible,
but in practice, it can be a major problem.

> >> - opposed to what?
> >
> > As opposed to an interface being able to specify thread-safety.
>
> I still don't understand how that is specific to interfaces.

Did I suggest that it was specific to interfaces?  If so, please quote
where I said that.

Signature

Regards,

John McGrath

Christian Kaufhold - 21 Jan 2005 20:26 GMT
Hello!

>> Similarly, just as implementing a class and documenting that it
>> is thread-safe (by whatever definition), one can require (in the
[quoted text clipped - 6 lines]
> thread-safety in the documentation and specifying it in the class /
> interface definition?  If so, I would disagree.  If class or interface

I'm not saying that. I'm just saying that just because something can
not be specified formally (because of language deficiency or because the
notion is too complicated to capture formally) doesn't mean that it does
may not belong to the specification just like the parts that can be
specified (e.g. argument types).


> I do not understand your point.  Your question was, "how can non-abstract
> classes ... specify thread-safety?"  How can the answer to that not depend
> on the definition of thread-safety?

It would be the same for any other notion that cannot be specified
formally.

> That definition was not explicit enough.  Please amend it to include the
> phrase "without external synchronization".  Of course, one problem with
> adding external synchronization is that it requires that you know every
> bit of code that might try to access the class, and that you consistently
> apply the synchronization using the same lock.  This is always possible,
> but in practice, it can be a major problem.

But internal synchronization is not useful if the state of the object
enters into argument values etc, e.g. how can you determine the index
argument for Document.insertString without making sure that the Document
is not modified between the determination of the index and the actual
call - assuming that the Document implementation does internal synchro-
nization.


>> >> - opposed to what?
>> >
[quoted text clipped - 4 lines]
> Did I suggest that it was specific to interfaces?  If so, please quote
> where I said that.

I thought it was implied by "interfaces cannot specify thread-safety"
as opposed to "in Java you cannot specify thread-safety".

Christian
Signature

The cat in the hat came back, wrecked a lot of havoc on the way
Always had a smile and a reason to pretend

                                R.E.M., The Sidewinder Sleeps Tonight

John McGrath - 23 Jan 2005 01:08 GMT
> >> For a user of that class or subclasses or classes that
> >> implement that interface there is no difference.
[quoted text clipped - 8 lines]
> may not belong to the specification just like the parts that can be
> specified (e.g. argument types).

Of course that is true.  But that does not mean that it makes no
difference whether you can specify it formally, as part of the code.
There is a *huge* advantage if you can do that.

> > I do not understand your point.  Your question was, "how can
> > non-abstract classes ... specify thread-safety?"  How can the answer
> > to that not depend on the definition of thread-safety?
>
> It would be the same for any other notion that cannot be specified
> formally.

But that assumes that the notion of thread-safety cannot be specified
formally.  But whether or not it can be specified depends on the
definition of thread-safety.  Take one definition:  FOLDOC defines
"thread-safe" as code that "is either re-entrant or protected from
multiple simultaneous execution by some form of mutual exclusion."
Clearly, that can be formally specified.

> But internal synchronization is not useful if the state of the object
> enters into argument values etc, e.g. how can you determine the index
> argument for Document.insertString without making sure that the Document
> is not modified between the determination of the index and the actual
> call - assuming that the Document implementation does internal synchro-
> nization.

This is the point that I made a few messages back.  I do not understand
why you are repeating it.

> > Did I suggest that it was specific to interfaces?  If so, please quote
> > where I said that.
>
> I thought it was implied by "interfaces cannot specify thread-safety"
> as opposed to "in Java you cannot specify thread-safety".

No, that was an incorrect inference.  "A implies B" does not mean "not A
implies not B".  We were talking about JTextArea's uses of the Document
interface, so I talked about interfaces.

Signature

Regards,

John McGrath



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.