views:

198

answers:

1

Is there a good, platform-agnostic way to implement a variable that's local to both a thread and a class instance, i.e. if you have T threads and I class instances, you have TxI instances of that variable? I'm using the D programming language, version 2, but a good language-agnostic answer would also be useful.

Here are some constraints:

  1. Must never require synchronization. This rules out having a hash table mapping thread ID to variable reference as a member variable.
  2. Must not keep references around that should be garbage-collected. This rules out having a thread-local, static hash table indexed by class instance.
  3. Initialization should be lazy for efficiency. If a thread never accesses a given instance's variable then it should never be created.
+2  A: 

Must not keep references around that should be garbage-collected. This rules out having a thread-local, static hash table indexed by class instance.

Use a hashtable with weak-referenced keys. Won't prevent garbage collection, and will drop the information from the hashtable when the key (the class instance) is collected.

Anon.
Decent idea, except there are no weak references in D right now.
dsimcha
Does it have finalizers?
Anon.
@Anon: Yes, D does have finalizers.
dsimcha
Then, presuming you can generate a unique hash for each object, you can still do something similar. Use the unique hash as the key for the hashmap, and in the object finalizer post an event to each thread to remove it from the hashmap.
Anon.
How does the finalizer ever get called if there are still references to the object?
dsimcha
There aren't. You use the unique hash as the key for the hashmap (so it doesn't have a reference to the object itself), and get the object to clean it up in the finalize.
Anon.