TAD - Thread Attached Data
Thread Associated Data (TAD) is a Java library that allows you to make state and services encapsulated in objects available to other objects within the execution of a single thread. For example in the doGet() method of a servlet you might attach the a User and database connection to the 'context' of the current thread so that it is available on demand everywhere else in the same thread.
In many respects, TAD solves similar problems as those addressed by dependency injection and can be used as an add-on and in some cases a direct replacement.
TAD is dynamic, very lightweight and extremely simple to use.
Links and stuff
- GitHub: https://github.com/inexas/tad
- Sonatype OSS repository: https://oss.sonatype.org/#nexus-search;quick~com.inexas
- Gradle: compile 'com.inexas:tad:0.1.0'
For the impatient...
- Lines 2..7: Define a TAD class that contains state that we want to attach to the current thread. The class must implement the Tad interface otherwise you can publish any state you wish or provide a service to be used elsewhere in the thread.
- Line 10: Instantiate an instance of our TAD class.
- Line 11: Attach the TAD class to the current thread's context. Now the TAD class can be retrieved by any method in the same thread
- Line 15: Detach the TAD once we've finished with it. Placing it in a finally block is a good idea
- Lines 20..21: Retrieve and use the TAD class.
- All attached TADs must be detached when you're done with them. It's good practice to do this in the same method that you attached it. If you fail to remove TAD objects an exception will be thrown when the thread terminates.
- TAD objects attached to one thread's context are invisible to others.
Where to go from here...
- TAD user guide - to learn how to use the TAD library
- Pricing and licensing - for information on product pricing and licensing
- TAD versus dependency injection - an article comparing TAD and dependency injection