Re: Closures and Concurrency
Bill Venners <bill <at> artima.com>
2009-10-01 07:15:56 GMT
Hi Ross,
On Wed, Sep 30, 2009 at 10:05 PM, Ross Judson <rossjudson <at> gmail.com> wrote:
> It's arguable that if you intend to use a local variable on multiple
> threads, you should be requird to choose an appropriate synchronization
> mechanism. When doing so, you need to be aware of additional methods
> required to use the value appropriately.
>
> val changes = new AtomicInteger()
>
> instead of
>
> @volatile var changes = 0
>
> and then
> changes set newValue
>
> instead of
> changes = newValue
>
Yes. The compiler already does that kind of thing on IntRef, though
IntRef doesn't have getters and setters, just a public field.
> A variety of methods on AtomicInteger exist to properly guarantee thread
> safety. With @volatile, how would you guarantee:
>
> changes = changes + x
>
> You can't unless you carry along the implementation of AtomicInteger. At the
> compiler level, translating @volatile to operations on AtomicInteger would
> have to recognize common expressions and invoke the "right" methods on the
> Atomic classes. You can't translate the code above in a simple manner, like:
>
> changes.set(changes.get() + x)
>
> It needs to be translated as:
>
> changes.addAndGet(x)
>
I think you mean incrementAndGet, but regardless, that's not what
volatile means. Volatile doesn't offer any atomic operations, just
that threads will read what other threads write. But if you want to
get an increment a variable as one atomic operation, then you can't
use volatile. So I think all the compiler would need to do is call set
and get, because if it were to do this kind of thing, it should stick
100% to what volatile means elsewhere.
But your initial point is correct, it can be argued that the behavior
we have now is OK and people just need to take care of making things
work themselves. That's what I do right now in my multi-threaded
tests. I make my own atomic integers. The problem is that because
volatile in Scala is an annotation, you can put it on a local
variable, and it will compile. So it *looks* like it is volatile. In
Java, because volatile is a keyword, it won't compile if you try and
put it on a local variable (and of course it wouldn't make sense
because Java doesn't have true closures anyway).
Bill
> RJ
>
> On Tue, Sep 15, 2009 at 2:50 PM, Bill Venners <bill <at> artima.com> wrote:
>>
>> Hi David,
>>
>> Reusing the atomic classes is a good idea.
>>
>> Bill
>
>
--
--
Bill Venners
Artima, Inc.
http://www.artima.com