Reputation: 26617
I need to run all scheduled tasks/ threads executed by ScheduledExecutorService
at a lower priority(at MIN_PRIORITY
) than rest all other threads in the application. I have been doing this the following way, but is this the correct way to accomplish this ?
ScheduledExecutorService schdExctr = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setPriority(Thread.MIN_PRIORITY);
return t;
}
});
I think a better implementation would be this:
private ScheduledExecutorService schdExctr = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = Executors.defaultThreadFactory().newThread(r);
t.setPriority(Thread.MIN_PRIORITY);
return t;
}
});
Upvotes: 3
Views: 2468
Reputation: 1489
yes, that is the correct way, additionally you could look at Executors.DefaultThreadFactory
class source to see how default threads are named.
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.MIN_PRIORITY)
t.setPriority(Thread.MIN_PRIORITY);
return t;
}
where group
and namePrefix
are:
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
and threadNumber
is:
private final AtomicInteger threadNumber = new AtomicInteger(1);.
In your implementation you won't be needing the poolNumber
.
EDIT after question edit: The solution would be:
private ScheduledExecutorService schdExctr = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
private ThreadFactory defaultThreadFactory = Executors.defaultThreadFactory();
@Override
public Thread newThread(Runnable r) {
Thread t = defaultThreadFactory.newThread(r);
t.setPriority(Thread.MIN_PRIORITY);
return t;
}
});
Upvotes: 3