Reputation: 6835
I have an object that is being used to update a database using a multithreaded methodology.
Now, I do not want to crash my db connection by overwhelming it with update attempts, and want to wait if i have a certain number of threads live.
my class that implements Runnable
is called updateUnmarked
.
now, i want to only launch a new thread if my thread count is < X
Thread.getAllStackTraces().keySet().size()
does not seem to work, and also the following does not seem to solve it:
public static int getLiveThreads(){
ThreadMXBean bean = null;
bean = ManagementFactory.getThreadMXBean();
return bean.getThreadCount();
}
both return 8 only...but i definitely have more than 8 threads.
Any idea how to do this?
Thanks!!!
Upvotes: 1
Views: 2037
Reputation: 31
I think it is cleaner to use the spring's threadpool executer service here
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="5" />
<property name="maxPoolSize" value="10" />
<property name="queueCapacity" value="25" />
</bean>
Upvotes: 0
Reputation: 116878
now, i want to only launch a new thread if my thread count is < X
Sounds to me that what you need is a thread-pool executor. Updates to your database can be submitted to the pool for execution and you can limit the number of concurrent requests to the database by limiting the number of threads assigned to the pool:
// create a thread pool with a max of 4 concurrent threads
ExecutorService threadPool = Executors.newFixedThreadPool(4);
// submit your database operation to the thread-pool
threadPool.submit(new DatabaseUpdateJob(databaseConnection, updateStatement));
...
public class DatabaseUpdateJob implements Runnable {
// you can construct your jobs and pass in context for them if necessary
public DatabaseUpdateJob(Connection dbConnection, String statement) {
...
}
public void run() {
// use the connection here to update the database
}
}
If you really want to do it yourself then Thread.activeCount()
should definitely work. It returns the number of active threads in the current thread-group. What you need to do is take a snapshot of the number of threads before your start your database work. There are a number of system threads that run in the background doing various tasks that you should ignore. Then whenever you take a new count, you can subtract the background threads and only track you database threads.
But a thread-pool is always a good idea.
Upvotes: 2