[concurrency-interest] thread safety of java.lang.reflect.Field

Jonas Konrad me at yawk.at
Thu May 31 14:33:02 EDT 2018


I can't speak for the standard, but caching Fields instances in static 
fields is *very* common so it's unlikely they would ever change the 
current behavior (it being safe to use).

If you are still concerned about correctness, VarHandle is specified to 
be "immutable and have no visible state" so that would be safe to share 
across threads.

- Jonas

On 2018-05-31 16:35, Novi via Concurrency-interest wrote:
>> I have not had any trouble with multiple threads using Fields 
>> concurrently.
> 
> Neither do I but that is no guarantee for correctness.
> (Compare for example this reflection related issue:
> https://bugs.openjdk.java.net/browse/JDK-8062771)
> 
> 
>> In other words, one still has to be mindful of concurrent access to 
>> the object's fields.
> 
> That is true but it is not what I meant to ask.
> 
> 
> Assuming that j.l.r.Field is thread safe in the current OpenJDK version, 
> is this
> merely an implementation detail or something that is guaranteed in future
> and/or other JVM implementations?
> 
> -Novi
> 
> 
> Am 31.05.2018, 14:11 Uhr, schrieb Nathan and Ila Reynolds via
> Concurrency-interest <concurrency-interest at cs.oswego.edu>:
> 
>> I usually cache Fields in private static final fields in the class 
>> that I use the Fields.  I have not had any trouble with multiple 
>> threads using Fields concurrently.  One caution is that if two threads 
>> execute the statement below concurrently on the same "obj", then one 
>> of the increments could be lost.  In other words, one still has to be 
>> mindful of concurrent access to the object's fields.
>>
>> s_field.setInt(obj, s_field.getInt(obj) + 1);
>>
>> -Nathan
>>
>> On 5/31/2018 3:31 AM, Novi via Concurrency-interest wrote:
>>> Hello,
>>>
>>> I wonder if instances of java.lang.reflect.Field can be shared between
>>> multiple threads as long as the accessibility flag is either not 
>>> modified
>>> or modified exactly once prior to a safe publication of the field
>>> instances.
>>>
>>> In other words, is it legal to cache instances of j.l.r.Field between
>>> multiple threads?
>>>
>>> Best Regards,
>>> Novi
>>>
>>>
>>> PS: The Bean Validation reference implementation Hibernate Validator 
>>> seems
>>> to cache instances of j.l.r.Field across threads. However, I couldn't 
>>> find any
>>> clue in the Java API documentation whether such a usage is supported or
>>> not.
>>> _______________________________________________
>>> Concurrency-interest mailing list
>>> Concurrency-interest at cs.oswego.edu
>>> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest


More information about the Concurrency-interest mailing list