How to implement ThreadLocal?

I want to have a ThreadLocal of an implementor of AutoCloseable. I can’t find some kind of hook where I can ensure close() is called when the thread dies.

Is this impossible?

1

  • This is a bad idea. Even if you could, you don’t want to do that.

  • … but you can’t do that, it’s impossible (without hackery that you really do not want to do).

It is impossible

See This SO question: How to add an event listener for the event ‘thread destroyed’.

There are routes for hackery. For example, you can hook yourself up to your own JVM as debug tool (JVMTI) which does get thread destruction events. But that’s not at all what JVMTI is for.

Even if it wasn’t, you don’t want to do that

Threads are routinely used in a pooling system. For example, a web server framework creates up to 100 threads to use to execute endpoint handlers (such as servlets). Those handlers might use ThreadLocal; after all, as long as that ThreadLocal is set before any handling code is executed, there is no risk that ThreadLocal has stale values.

However, these threads are never destroyed.

You might now think: Ah, see, no problem! Any attempt to .set a new value for this thread local will result in closing the previous value!

But that’s not going to solve the fundamental problem here. That doesn’t work in 2 ways:

  • Some code is free to get the thread local value, then spin off an entirely new thread, hand it the value, and wash its hands off of it. For example, a web framework gets a call to begin producing a report that will take quite a lot of time, so the handler fetches the request object (that encodes web path, parameters, etc – in the servlet API, HttpServletRequest) which ends up coming through via a ThreadLocal and hands it directly to the report generator which is then run in a separate thread, then this thread returns itself to the pool and thus soon that threadlocal will have it’s .set method called, which would result in closing the resource that the report generator is still using – a bug. One that will be quite difficult to write a test for!

  • Thread pool impls don’t tend to relinquish threads. Why do it? Given a system that now has 100 threads in the pool: We have proof that [A] the system has had to deal with a load that required 100 threads, and [B] we hve proof the system is resourcewise capable of handling that many or we’d have crashed already. So why give threads back? That’s just pointless bookkeeping work. Hence, they tend not to. Which means a thread can hang around, frozen, for days. If that means some file handle remains open for days because it requires 100 simultaneous connections for that thread to be ‘reused’, causing .set to be called, causing resource closing – and 100 simultaneous connections happen only once in a blue moon.

Of course it’s possible to imagine a system whereby none of these problems can ever occur. But APIs are abstractions. APIs that are ‘leaky’ are bad, even if the leaky aspects of it do not currently cause issues. (‘leaky’ = you need to know a ton of caveats, and cannot realistically be used correctly without knowing how they work under the hood, the abstraction is therefore ‘fake’ in that you can’t do the useful step of ignoring the underlying details and just trusting the API as doing what it says in the way one expects without first reading its source A through Z). An auto-closing threadlocal that comes with a list of caveats that includes statements like ‘no thread pools’, ‘must have consistent thread load’, ‘resources may stay open for a very long time’ – that’s not a good API even if you so happen to have a project that is compatible with all these bizarre requirements.

So how do I solve these problems?

Whatever chain of operations currently lead you to wanting an auto-closing ThreadLocal – draw it all out on a whiteboard and draw a big circle around it. This should result in a process that is time-wise constrained – the whole point of closing resources is that you don’t hold them open for potentially unbounded / extremely long times. Write a wrapper class that represents that entire process. It will manage the resource: It will open the resource, call the chain of events, track when that chain has completed (successfully or via error), and closes the resource once that happens.

General resource cleanliness

What does that mean when writing code that uses resources?

Any resource-using code needs to make a choice:

  1. The code makes the resource and ensures its closure inline with its creation. This is the simple case usually covered with try (var resource = createResource()) { /* use it here */ }.

  2. The code makes the resource and is itself a resource – it implements AutoClosable, and closes the resource it made in its own close() method. Any users of this code will, itself, have to treat the instance of your class as a resource, applying this same list of strategies to ensure it is done properly.

  3. The code does not make the resource, but is given it by the caller. However, this code spells out explicitly in its documentation that the code adopts the resource. The code will take care of closing it, and the caller must not interact with the resource in any way afterwards. This is important: Shared responsibility is no responsibility; attempting to set up a system whereby multiple unrelated slices of code all use the same resource haphazardly and ‘last one to leave the room, please turn off the light’ – that’s not going to work. Trying to set up a system where some external aspect (such as a ThreadLocal attempting to watch for its thread dying) eventually realizes someone left the light on does not work either. After all, if it did, we’d just stick to the 1990 plan of cleaning up a resource if the object that represents it gets garbage collected. Which you can do, and is a horrible idea, explicitly strongly recommended against by the JDK spec itself. Once adopted the strategy must use item 1 or 2 on this list.

  4. The code does not make the resource but is given it by the caller. The code spells out that it is not responsible for the resource and will therefore not close it. This inherently means that the code must use the resource only in the lexical confines of this call – it cannot ‘save’ the resource in a field to use later, or hand it off to another thread.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật