[concurrency-interest] Joda-Time immutability

Attila Szegedi szegedia at gmail.com
Mon Jun 20 13:44:20 EDT 2011


You are right, Mark. If the field is read reflectively - replacing "tff.x" with "f.get(tff)" in the println invocation - to avoid any compile-time optimizations, it will actually print 2. 

Attila.

On Jun 20, 2011, at 10:23 AM, Mark Thornton wrote:

> On 20/06/11 17:52, Attila Szegedi wrote:
>> 
>> Well, to me it looks like it's implemented:
>> 
>> import java.lang.reflect.Field;
>> 
>> public class TestFinalField {
>>   public final int x = 1;
>> 
>>   public static void main(String[] args) throws Exception {
>>     TestFinalField tff = new TestFinalField();
>>     Field f = tff.getClass().getField("x");
>>     f.setAccessible(true);
>>     f.set(tff, 2);
>>     System.out.println(tff.x);
>>   }
>> }
>> 
>> This prints "1", and not "2". So, setting of a final field is actually silently ignored with setAccessible(true), for better or worse. Without setAccessible(), it will actually throw an exception. With the "final" qualifier removed from the field, it prints "2", as expected. I tested it with both latest Java 6 and on the b145 build of OpenJDK 7, and both behaves as described.
>> 
>> Attila.
>> 
> I think what is happening here is that the object is being updated, but the print statement is being 'optimised'.
> 
> Mark
> 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20110620/24911f32/attachment.html>


More information about the Concurrency-interest mailing list