let's play TDD, tackles closures in java

Brian Goetz brian.goetz at oracle.com
Mon Dec 20 03:21:12 PST 2010

FYI, this was one of the directions we explored and rejected for Java 8.  In addition to the problematic "magic" issue you identified, it has another problem: it does not provide a general mechanism for read-modify-write updates.  It works for += and friends but not for other read-modify-write use cases.  But making the simple cases work simply lulls users into a false sense of security, and when they try to write code like

  int counter=n;
  foo.addListener(#{ e -> 
           if (counter > 0)

they might reasonable expect counter to never be negative, and might be surprised.  

On Dec 18, 2010, at 5:17 PM, Artur Biesiadowski wrote:

> On 16/12/2010 08:30, Florian Weimer wrote:
>> We can turn this into:
>> final BooleanReference fired = new BooleanReference(false);
>> model.addTableModelListener(#{e ->  fired.setValue(true)});
>> model.doThing();
>> assertTrue(fired.getValue());
> You can as well use AtomicBoolean, which has an extra benefit of having 
> defined behaviour in multithreaded case.
> I suppose that 95% of the cases of 'ugliness' people are rising could be 
> solve by adding kind of autoboxing for Atomic* classes.
> AtomicBoolean fired = false;
> model.addTableModelListener(#{e ->  fired = true;});
> model.doThing();
> assertTrue(fired.get()); // or assertTrue((boolean)fired); or even assertTrue(fired) as assertTrue is expecting boolean only, not object ref
> With mapping of AtomicInteger.addAndGet to +=, ++,-- to 
> increment/decrementAndGet, you will even get multithreaded sum thing 
> working out of the box.
> While I'm not big fan of another set of magic dependencies (after String 
> contatenation and java.lang.Integer/etc autoboxing), I still find it a 
> lot cleaner that most of the solutions for transparent shared variable 
> access.
> Regards,
> Artur Biesiadowski

More information about the lambda-dev mailing list