opwvhk commented on code in PR #2900: URL: https://github.com/apache/avro/pull/2900#discussion_r1622618815
########## lang/java/avro/src/main/java/org/apache/avro/reflect/ReflectData.java: ########## @@ -379,12 +379,14 @@ private ClassAccessorData(Class<?> c) { * Return the field accessors as an array, indexed by the field index of the * given schema. */ - private synchronized FieldAccessor[] getAccessorsFor(Schema schema) { - // if synchronized is removed from this method, adjust bySchema appropriately + private FieldAccessor[] getAccessorsFor(Schema schema) { + // to avoid synchronization, we replace the map for each modification FieldAccessor[] result = bySchema.get(schema); if (result == null) { result = createAccessorsFor(schema); + Map<Schema, FieldAccessor[]> bySchema = new WeakHashMap<>(this.bySchema); bySchema.put(schema, result); + this.bySchema = bySchema; Review Comment: The remark about `volatile` is valid: that's exactly what it does. Also a few notes about `WeakHashMap`: 1. it has weak keys, so it'll only cleanup entries that can no longer be looked up 2. its internal hash table is a singly-linked list, and the update to remove an entry is an atomic operation (that never yields an invalid data structure) 3. the update happens without a memory barrier, which means that the worst case scenario is that the update is not yet available to the other thread, which means that the entry to be removed is read & skipped over in the concurrent call to `get` In practical terms, this means that because the we update a *copy* of the `WeakHashMap` before it becomes available, and it's only modified to expunge stale entries after it becomes available, the result is effectively thread safe. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: issues-unsubscr...@avro.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org