[concurrency-interest] synchronized constructors

Martin Buchholz martinrb at google.com
Mon Dec 19 16:40:56 EST 2011


On Sun, Dec 18, 2011 at 13:56, Vitaly Davidovich <vitalyd at gmail.com> wrote:

> Hi Martin,
>
> This seems a bit dubious since you can just mark your fields final.
>  What's the advantage of the dummy assignment? In Roland's case, he
> couldn't assign one of the fields in the constructor because it has to be
> done via a setter post construction but before publishing.
>
>
The idea is to prevent readers from ever observing the state of any of the
fields before the constructor completes.  For example, this can be used to
guarantee that the Object x in my example is never null.  Mutation after
construction is permitted (for example, all methods might be synchronized).

This is more of a thought experiment than a practical technique.  Most
people are OK with writing code that is incorrect, but never observed to
fail in practice, especially when there's safety in numbers.

Martin


> Regards,
>
> Vitaly
>
> On Sun, Dec 18, 2011 at 4:22 PM, Martin Buchholz <martinrb at google.com>wrote:
>
>>
>>
>> On Sun, Dec 18, 2011 at 13:02, Roland Kuhn <rk at rkuhn.info> wrote:
>>
>>> Yes, I would very much welcome a simple way achieving a fence, as you
>>> might imagine ;-)
>>>
>>
>> Many of us here would like to see a way to safely publish an object.
>>
>> ---
>>
>> Here's a solution no one has mentioned, but ought to be bullet-proof:
>>
>> public class MutableSafePublication {
>>     private int i;
>>     private Object x;
>>     private final MutableSafePublication safePublicationThis;
>>     private int i() { return safePublicationThis.i; }
>>     private Object x() { return safePublicationThis.x; }
>>     public MutableSafePublication() {
>>         i = 42;
>>         x = new Object();
>>         safePublicationThis = this;
>>     }
>>     // use i() and x() consistently in the implementation
>> }
>>
>>
>
>
> --
> Vitaly
> 617-548-7007 (mobile)
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20111219/f66caa33/attachment-0001.html>


More information about the Concurrency-interest mailing list