James Watson
Posts: 2024
Nickname: watson
Registered: Sep, 2005
|
|
Re: From JavaOne 2009: On Trust and Types
|
Posted: Jun 15, 2009 9:13 AM
|
|
> > the closure solution couldn't enforce correct usage
> It does. You can enforce using the closure in a library, but it would be quite hard to use.
I know it does. I was pointing out that you implied it didn't. What is so difficult about it?
> I'm used to. Runnable, Arrays.sort(.., Comparator) and so > on. It is hard to use: How do you change a variable of the > outer block in the inner block? It's possible (for example > using one-element arrays) but it's ugly. Even accessing a > variable of the main block is complicated (you need to > make it final). The closure (Block.execute in the example > above) needs to declare exception(s) the block can throw, > and the caller has to catch that (even if he doesn't throw > any). Or you don't declare, but then the caller can't use > checked exceptions. Then the size of the code is bigger.
I don't see how declaring a variable final is complicated. It's just an extra keyword. In fact, I think Java would be a much better language if variables defaulted to final and had to be explicitly declared to be writable.
I use this approach all the time. The need to modify a local variable from the rarely comes up and you can always use a named local class, inner class, or nested class to avoid the issue entirely.
Exception handling is a downside but again, in the infrequent cases that I need to, it's worth wrapping and unwrapping the runtime errors. The size of the code is not a real issue, in my opinion.
> > I think you mean each and every library. > > Also, each library needs to do this. > > Well, obviously. I'm quite sure you didn't understand my > solution, otherwise you wouldn't ask. The 'synchronized' > solution enforces using synchronized in the client code, > if the 'synchronized' solution is used in the library.
I understand the approach perfectly and I'm not asking. I'm clarifying. As stated you made it sound as if the solution enforced correct usage in itself which you are now readily admitting that it does not. The closure solution does enforce correct usage in itself.
Basically, the solution you are proposing requires that all work with the resource object be executed within the same stack as the request to get the resource object. You can't easily pass this resource to another class for it to use. This limits the kinds of designs you can use with this approach. You can't easily reuse this resource object or share it with other parts of the code.
The real problem I see with the synchronization solution, other than being inelegant is that synchronization is associated with many types of usage errors in itself. Many of these usage errors are extremely difficult to find in code and can depend on the JVM, platform, or hardware.
|
|