Huh, I've been using HashMaps (actually HashTable, the Evil Synchronized Sibling of HashMap) for this sort of thing for years, even naming them things like "threadLocalPool." Despite all the hassles of synchronization and releasing objects at thread death, it never occurred to me to check whether there was a built in class that does it for you.
Apparently the first implementations were real bad performance-wise, so it never took off, but it looks like the recent ones are just fine. Good to know...
Looks like the thing to do would be to subclass ThreadLocal for each type that we need to grab local versions of, i.e.:
...etc. (sadly, we can't do it generically because type erasure makes returning a new instance of the generic type impossible, so we actually need to write a version for each type that we want to use 🙁 )
Then we'd pop one in place of each private static member currently being used. Refactoring-wise, probably easiest to start with "Encapsulate field" on each private static, then just edit the getter/setter to access the ThreadLocal instead. Come to think of it, depending on the performance hit, we might even be able to keep the two options side by side (i.e. use the ThreadLocal for possible multithreaded environments, but the private static variable for single threaded cases) just by switching a global flag, but we can worry about that later if the performance is an issue.
Apparently the first implementations were real bad performance-wise, so it never took off, but it looks like the recent ones are just fine. Good to know...
Looks like the thing to do would be to subclass ThreadLocal for each type that we need to grab local versions of, i.e.:
Code:
public class ThreadLocalVec2 extends ThreadLocal<Vec2> {
protected Vec2 initialValue() {
return new Vec2();
}
}
public class ThreadLocalMat22 extends ThreadLocal<Mat22> {
protected Mat22 initialValue() {
return new Mat22();
}
}
protected Vec2 initialValue() {
return new Vec2();
}
}
public class ThreadLocalMat22 extends ThreadLocal<Mat22> {
protected Mat22 initialValue() {
return new Mat22();
}
}
...etc. (sadly, we can't do it generically because type erasure makes returning a new instance of the generic type impossible, so we actually need to write a version for each type that we want to use 🙁 )
Then we'd pop one in place of each private static member currently being used. Refactoring-wise, probably easiest to start with "Encapsulate field" on each private static, then just edit the getter/setter to access the ThreadLocal instead. Come to think of it, depending on the performance hit, we might even be able to keep the two options side by side (i.e. use the ThreadLocal for possible multithreaded environments, but the private static variable for single threaded cases) just by switching a global flag, but we can worry about that later if the performance is an issue.