Re: Thread safety documentation
Tom Anderson wrote:
<snipage>
I wouldn't be surprised if they'd rejected the idea including compiler
proof. But the annotations seem so uncontroversial and obviously a good
idea that i'm shocked that they weren't considered.
I'm a little shocked also, esp that it wasn't taken up to then add to
the API. (That is, add some annotations in the API like
javax.threading.NotThreadSafe and such-like). It seemed a bit like one
part of Sun doesn't talk to the other part, but sometimes that happens
in large corporations.
It would. But i rather doubt it's practical - how exactly would the
compiler do that? On the face if it, that sounds like a very hard
(halting-problem-hard) thing to prove in general.
I imagine it would work like this. Define an annotation like this:
RequiresThread( String s );
Then apply it to appropriate Java classes. E.g.:
@RequiresThread( "EDT" )
public class JFrame { ...
@RequiresThread( "EDT" )
public class JLabel { ...
Now these annotation must be propagated or satisfied, a bit like
throwing exceptions.
@RequiresThread( "EDT" )
private void createAndShowGui() {
JFrame frame = new JFrame( "A Test" );
frame.add( new JLabel( "This is a test" ) );
frame.pack();
frame.setVisible( true );
}
Without the "@RequiresThread( "EDT" )" that method won't compile. It
doesn't satisfy the threading condition required by the classes (or
methods) it uses, so we must propagate it.
So we keep going:
@RequiresThread( "EDT" )
Runnable r = new Runnable() {
public void run() {
createAndShowGui();
}
};
Yeah that Runnable isn't safe either. So again we have to propagate the
annotation. Now SwingUtilities.invokeLater() would have to be declared
with something like
@SatisfiedThread( "EDT" )
public static void invokeLater( Runnable r ) {...
Which is just another annotation. Now we can do this:
public static void main( String... args ) {
SwingUtilities.invokeLater( r );
}
And voila! We don't have to propagate the @RequiresThread( "EDT" )
anymore, because it was satisfied.
More realistically, we probably have to find a way to specify exactly
which argument(s) satisfy the threading requirement, but I'll leave that
off for now as busy-work.
This doesn't prove my program correct, of course. It just checks that I
did the right thing, according to some publicly declared API (with
annotations). The idea isn't to make all code is correct, just make
sure library writers can specify the thread safety of their own
libraries (and APIs) and users won't have to read carefully to make sure
they've met the requirements. It'll be right in front of them, for
starters, and also the compiler can check too.
I'm sure there's more (any more) use cases than this, but that's where
my thinking starts. I haven't (for example) thought about how to make a
SwingWorker with annotations like these. I guess that could be the next
bit.