DMor
DMor

Reputation: 789

How to properly create and implement a ThreadPool type class in Java

I would like to make my own ThreadPool type class in Java (I tried in the past and kept getting concurrent exceptions - I forgot the specific error) and i'm back to it again.

This would be used to on the fly, easily create different threads to run different processes concurrently and then when a task finishes in the thread it was passed to, it would be recycled and reused for another purpose. This is for a 2d game engine in Java that I coded myself.

This would be used for things such as collision, audio, animation management, timing, controls, etc. These are just options for the reason i need a ThreadPool class.

Problem: The last time I tried this, I created a ThreadPool class that held an Array of type "AudioThread" (or something similar) that was an inner class that overrided the "run" method. When creating a ThreadPool class, I would pass a number of threads to be created and that would be stored in the array for later manipulation.

I would then try to create methods such as "assignTask(ThreadTask task)", "freeThread()", getFreeThread(). etc. But from making changes to the threads, I got concurrent errors of some sort.

Bottom line, does anyone have experience making a ThreadPool type class that can offer experience to what I can and cant do? Suggestions for fixing this problem? Advice? Thoughts?

Thank you.

Upvotes: 0

Views: 287

Answers (1)

John Watts
John Watts

Reputation: 8875

You probably want to use ThreadPoolExecutor. It sounds like it does exactly what you want.

Upvotes: 1

Related Questions