How to set the Thread priority of a Timer in java? This is the code I have found in the project that I am working on, and I do not think that it is working:
public static Timer createNamedTimer(boolean isDaemon,
final String threadName, final int priority) {
Timer timer = new Timer(isDaemon);
timer.schedule(new TimerTask() {
public void run() {
Thread.currentThread().setName("TimerThread: " + threadName);
Thread.currentThread().setPriority(priority);
}
}, 0);
return timer;
}
AFAIK for timer the only way you can change priority is the way you are doing it.
If you need a better option you can use the ThreadFactory for creating the threads and setting their priority.
class SimpleThreadFactory implements ThreadFactory {
private int threadPriority;
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setPriority(threadPriority);
return t;
}
}
Then you can pass the factory to the Executors framework of Java for doing what you want, IMHO this will be a much better approach.
Why do I say it would be a better approach?
The Timer class's JavaDoc mentions ScheduledThreadPoolExecutor and notes, that this class is effectively a more versatile replacement for the Timer/TimerTask combination
The suggested solution won't likely work for tasks that are repeated more than once, because between invocations another task that shared the same thread may have adjusted the priority to something else. Therefore, for repeating tasks you must set the priority at execution time, every time. This potential issue exists w/or w/o the new Executors framework.
One solution is to create a wrapper class that does prep work for you to ensure consistency. For example:
AnyClass.java:
private static void exampleUsage()
{
try { launchHighPriorityTask(() -> System.out.println("What a fancy task.")).join(); }
catch (Throwable ignored) {}
}
private static Thread launchMaxPriorityTask(Runnable task)
{
final Thread customThread = new Thread(new Task("MaxPriority", Thread.MAX_PRIORITY, task));
customThread.start();
return customThread;
}
Task.java:
public class Task implements Runnable
{
private final String name;
private final int priority;
private final Runnable task;
public Task(String name, int priority, Runnable task)
{
if (null == task) throw new NullPointerException("no task provided");
this.name = name; this.priority = priority; this.task = task;
}
/**
* run() is made final here to prevent any deriving classes
* accidentally ruining the expected behavior
*/
#Override public final void run()
{
final Thread thread = Thread.currentThread();
// cache the current state to restore settings and be polite
final String prevName = thread.getName();
final int prevPriority = thread.getPriority();
// set our thread's config
thread.setName(name);
thread.setPriority(priority);
try { task.run(); } catch (Throwable ignored) {}
// restore previous thread config
thread.setPriority(prevPriority);
thread.setName(prevName);
}
}
This is naturally a minimalist example of what can be accomplished with this sort of setup.
Related
I'd like to make a ThreadPollExecutor that executes tasks with a given priority Process.setThreadPriority(int).
How should I do it? Adding the call to setThreadPriority at the start of each runnable sent to the thread poll? I've also considered using a custom thread factory like this:
private final static class ProcessPriorityThreadFactory implements ThreadFactory {
private final int threadPriority;
public ProcessPriorityThreadFactory(int threadPriority) {
super();
this.threadPriority = threadPriority;
}
#Override
public Thread newThread(Runnable r) {
return new Thread(new PriorityChangeWrapper(r, threadPriority));
}
private final static class PriorityChangeWrapper implements Runnable {
private final Runnable originalRunnable;
private final int threadPriority;
public PriorityChangeWrapper(Runnable originalRunnable, int threadPriority) {
super();
this.originalRunnable = originalRunnable;
this.threadPriority = threadPriority;
}
#Override
public void run() {
Process.setThreadPriority(threadPriority);
originalRunnable.run();
}
}
}
What is the best solution for this problem? Thanks
The custom factory as given in your question is the correct way to do this. The factory pattern is used for just this reason as it gives you total control over all the threads created by the ExecutorService. (For example you can also change the thread names etc).
Your implementation of the factory is much more complex than is needed though, all you need is:
private final static class ProcessPriorityThreadFactory implements ThreadFactory {
private final int threadPriority;
public ProcessPriorityThreadFactory(int threadPriority) {
this.threadPriority = threadPriority;
}
#Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setPriority(threadPriority);
return thread;
}
}
I have this pairing mechanism idea that identifies Clients by their ThreadID. When the thread is destroyed, the client's pairing is destroyed and its ID is set to -1.
Now in order for me to get the Thread ID, the thread must of course have been running or started.
I want to know if I can create a thread, get the ID and then set the runnable later on OR if I can get the ID of the current thread that's running my function..
Example of what I want to do:
void createClientThreaded(final Client client) {
new Thread(new Runnable() {
#Override public void run() {
while(!client.stop()) {
Utils.sleep(1000);
//Do other stuff here..
client.setThreadID(/* This Thread's ID */);
// Do other stuff here..
}
}
});
}
Any ideas on how I can do this? Also would the Thread ID's be unique per process or unique for the whole system? In other words, can two jar files running at the same time have the same Thread ID?
The thread id is immutable, so you won't be able to set it to -1 when the thread terminates.
The id is created as soon as the thread is created, not as soon as the thread is started, so you can create the thread, read its id, and start it later.
However, if you're creating and destroying a lot of threads, then you're going to incur a high runtime cost. It would be more efficient to use a ThreadPoolExecutor to execute your runnables, however this precludes the option of creating a thread, reading its id, and starting the thread later. Another option is to create your own class that implements Runnable with a mutable id.
class MyRunnable implements Runnable {
private static AtomicLong idCounter = new AtomicLong(0);
private long id;
public MyRunnable() { this.id = idCounter.getAndIncrement(); }
public void setId(long id) { this.id = id; }
public long getId() { return this.id; }
public void run() {}
}
Thread ids are per process, not system-wide. In addition, the process may reuse thread ids (e.g. if the thread with id=5 terminates, then the process may assign id=5 to a new thread).
To run a runnable at some later time:
import java.util.concurrent.Semaphore;
public class Main {
public static void main(String[] args) {
DelayedExecutionThread blocker = new DelayedExecutionThread();
Thread t = blocker.getThread();
t.start();
System.out.println("Thread Started..");
sleep(3000);
System.out.println("Executing..");
blocker.setRunnable(new Runnable() {
#Override
public void run() {
System.out.println("RAN THE THREAD LATER");
}
});
sleep(1);
System.out.println("Executed..");
}
private static class DelayedExecutionThread {
private Semaphore lock = new Semaphore(1, true);
private Thread thread;
private Runnable target;
public DelayedExecutionThread() {
this.lock.acquireUninterruptibly();
this.thread = new Thread(new Runnable() {
#Override
public void run() {
DelayedExecutionThread.this.lock.acquireUninterruptibly();
DelayedExecutionThread.this.lock.release();
DelayedExecutionThread.this.lock = null;
if (DelayedExecutionThread.this.target != null) {
DelayedExecutionThread.this.target.run();
}
}
});
}
public Thread getThread() {
return this.thread;
}
public void setRunnable(Runnable runnable) {
this.lock.release();
this.target = runnable;
}
}
private static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
I used a semaphore. You just need some sort of locking or condition. When the thread is started, it attempts to acquire the lock which causes it to "wait" until it can acquire it. When you set the runnable at some later point in time, it will release the lock causing the thread to acquire it, release it, and continue execution.
I have two tasks: The first task (work) is reoccurring and the second task (cleanup) is releases some resources. The cleanup task should be run exactly once after the reoccurring work task has completed and will not be run again.
My first instinct was something like this:
ScheduledExecutorService service = ...;
ScheduledFuture<?> future = service.scheduleAtFixedRate(work, ...);
// other stuff happens
future.cancel(false);
cleanup.run();
The problem here is that cancel() returns immediately. So if work happens to be running, then cleanup will overlap it.
Ideally I would use something like Guava's Futures.addCallback(ListenableFuture future, FutureCallback callback). (Guava 15 may have something like that).
In the meantime, how can fire a callback when future is cancelled and work no longer running?
This is the solution that I've come up with. It seems to be pretty simple, but I still assume there's a more common and/or elegant solution out there. I'd really like to see one in a library like Guava...
First I create a wrapper to impose mutual exclusion on my Runnables:
private static final class SynchronizedRunnable implements Runnable {
private final Object monitor;
private final Runnable delegate;
private SynchronizedRunnable(Object monitor, Runnable delegate) {
this.monitor = monitor;
this.delegate = delegate;
}
#Override
public void run() {
synchronized (monitor) {
delegate.run();
}
}
}
Then I create a wrapper to fire my callback on successful invokations of cancel:
private static final class FutureWithCancelCallback<V> extends ForwardingFuture.SimpleForwardingFuture<V> {
private final Runnable callback;
private FutureWithCancelCallback(Future<V> delegate, Runnable callback) {
super(delegate);
this.callback = callback;
}
#Override
public boolean cancel(boolean mayInterruptIfRunning) {
boolean cancelled = super.cancel(mayInterruptIfRunning);
if (cancelled) {
callback.run();
}
return cancelled;
}
}
Then I roll it all together in my own method:
private Future<?> scheduleWithFixedDelayAndCallback(ScheduledExecutorService service, Runnable work, long initialDelay, long delay, TimeUnit unit, Runnable cleanup) {
Object monitor = new Object();
Runnable monitoredWork = new SynchronizedRunnable(monitor, work);
Runnable monitoredCleanup = new SynchronizedRunnable(monitor, cleanup);
Future<?> rawFuture = service.scheduleAtFixedRate(monitoredWork, initialDelay, delay, unit);
Future<?> wrappedFuture = new FutureWithCancelCallback(rawFuture, monitoredCleanup);
return wrappedFuture;
}
I'll give it another shot then. Either you may enhance the command or you may wrap the executed Runnable/Callable. Look at this:
public static class RunnableWrapper implements Runnable {
private final Runnable original;
private final Lock lock = new ReentrantLock();
public RunnableWrapper(Runnable original) {
this.original = original;
}
public void run() {
lock.lock();
try {
this.original.run();
} finally {
lock.unlock();
}
}
public void awaitTermination() {
lock.lock();
try {
} finally {
lock.unlock();
}
}
}
So you can change your code to
ScheduledExecutorService service = ...;
RunnableWrapper wrapper = new RunnableWrapper(work);
ScheduledFuture<?> future = service.scheduleAtFixedRate(wrapper, ...);
// other stuff happens
future.cancel(false);
wrapper.awaitTermination();
cleanup.run();
After calling cancel, either work is no longer running and awaitTermination() returns immediately, or it is running and awaitTermination() blocks until it's done.
Why don't you do
// other stuff happens
future.cancel(false);
service.shutdown();
service.awaitTermination(1, TimeUnit.DAYS);
cleanup.run();
This will tell your executor service to shutdown, thus allowing you to wait for the possibly running work to be finished.
How do i check if a thread is running in the pool of thread ExecutorService?
Background:
I want to synchronize between the threads in the Thread pool if there is a flag set.
So if the flag is set to true for synchronization, then I have to check if other Threads are running or wait for its completion and then invoke the blocking thread with synchronize, so that other threads would wait for this blocking thread to finish.
If flag is not set then no need to synchronize and could execute the threads in parallel.
Thanks!
You need to use a Semaphore.
This allows you to have a number of "permits" to do work. If you only want one task running at a time then have a Semaphore with one permit, otherwise have a Semaphore with a number of permits greater than the number of Threads in the pool.
static class Worker implements Runnable {
final Semaphore semaphore;
public Worker(Semaphore semaphore) {
this.semaphore = semaphore;
}
#Override
public void run() {
try {
semaphore.acquire();
try {
//do stuff
} finally {
semaphore.release();
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
public static void main(String[] args) {
final int numThreads = 10;
final ExecutorService executorService = Executors.newFixedThreadPool(10);
final Semaphore semaphore;
boolean myflag = true;
if (myflag) {
semaphore = new Semaphore(1);
} else {
semaphore = new Semaphore(numThreads);
}
final Worker worker = new Worker(semaphore);
executorService.submit(worker);
}
This example is a little contrived as you can just use a newSingleThreadExecutor() when you only need one task to run at a time - but I assume you know that and for some reason cannot.
EDIT
Having poked around a little to see if this can be tidied I came across this. This hints at a neater solution:
static interface TaskBlocker {
void acquire();
void release();
}
static class Worker implements Runnable {
final TaskBlocker taskBlocker;
public Worker(TaskBlocker taskBlocker) {
this.taskBlocker = taskBlocker;
}
#Override
public void run() {
taskBlocker.acquire();
try {
//do stuff
} finally {
taskBlocker.release();
}
}
}
public static void main(String[] args) {
final int numThreads = 10;
final ExecutorService executorService = Executors.newFixedThreadPool(numThreads);
final TaskBlocker taskBlocker;
boolean myflag = true;
if (myflag) {
taskBlocker = new TaskBlocker() {
final Lock lock = new ReentrantLock();
#Override
public void acquire() {
lock.lock();
}
#Override
public void release() {
lock.unlock();
}
};
} else {
taskBlocker = new TaskBlocker() {
#Override
public void acquire() {
}
#Override
public void release() {
}
};
}
final Worker worker = new Worker(taskBlocker);
executorService.submit(worker);
}
In short, you don't. Executors are not meant to be used that way. If you want to manage your threads manually, do it without Executors. If you use Executors, shift your thinking from Threads to Runnables. Make your Runnables or the Classes and methods thread-safe, using synchronization or any of the high-level abstractions in java.util.concurrent.
How do i check if a thread is running in the pool of thread ExecutorService?
If you just want to know if a thread is running in a specific ExecutorService, you can create the ExecutorService with a specific ThreadFactory and have it attach some special property to the thread, such as a special name.
private static final String EXECUTOR_THREADNAME_PREFIX = "ExecutorThread";
ThreadFactory threadFactory = new ThreadFactory() {
private final AtomicInteger id = new AtomicInteger(0);
#Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setName(EXECUTOR_THREADNAME_PREFIX + "_" + id.incrementAndGet());
return thread;
}
};
myExecutor = Executors.newCachedThreadPool(threadFactory);
Then, in the thread, you simply check if the name starts with your prefix:
if (Thread.currentThread().getName().startsWith(EXECUTOR_THREADNAME_PREFIX)) {
// In executor.
} else {
// Not in executor.
}
So, I'm curious. How do you handle setting maximum execution time for threads? When running in a thread pool?
I have several techniques but, I'm never quite satisfied with them. So, I figure I'd ask the community how they go about it.
How about:
Submit your Callable to the ExecutorService and keep a handle to the returned Future.
ExecutorService executorService = ... // Create ExecutorService.
Callable<Result> callable = new MyCallable(); // Create work to be done.
Future<Result> fut = executorService.submit(callable);
Wrap the Future in an implementation of Delayed whereby Delayed's getDelay(TimeUnit) method returns the maximum execution time for the work in question.
public class DelayedImpl<T> implements Delayed {
private final long maxExecTimeMillis;
private final Future<T> future;
public DelayedImpl(long maxExecTimeMillis, Future<T> future) {
this.maxExecMillis = maxExecMillis;
this.future = future;
}
public TimeUnit getDelay(TimeUnit timeUnit) {
return timeUnit.convert(maxExecTimeMillis, TimeUnit.MILLISECONDS);
}
public Future<T> getFuture() {
return future;
}
}
DelayedImpl impl = new DelayedImpl(3000L, fut); // Max exec. time == 3000ms.
Add the `DelayedImpl` to a `DelayQueue`.
Queue<DelayedImpl> queue = new DelayQueue<DelayImpl>();
queue.add(impl);
Have a thread repeatedly take() from the queue and check whether each DelayedImpl's Future is complete by calling isDone(); If not then cancel the task.
new Thread(new Runnable() {
public void run() {
while (!Thread.interrupted) {
DelayedImpl impl = queue.take(); // Perform blocking take.
if (!impl.getFuture().isDone()) {
impl.getFuture().cancel(true);
}
}
}
}).start();
The main advantage to this approach is that you can set a different maximum execution time per task and the delay queue will automatically return the task with the smallest amount of execution time remaining.
Normally, I just poll regularly a control object from the threaded code. Something like:
interface ThreadControl {
boolean shouldContinue();
}
class Timer implements ThreadControl {
public boolean shouldContinue() {
// returns false if max_time has elapsed
}
}
class MyTask implements Runnable {
private tc;
public MyTask(ThreadControl tc) {
this.tc = tc;
}
public void run() {
while (true) {
// do stuff
if (!tc.shouldContinue())
break;
}
}
}
Adamski:
I believe that your implementation of the Delayed Interface requires some adjustment in order to work properly. The return value of 'getDelay()' should return a negative value if the amount of time elapsed from the instantiation of the object has exceeded the maximum lifetime. To achieve that, you need to store the time when the task was created (and presumably started). Then each time 'getDelay()' is invoked, calculate whether or not the maximum lifetime of the thread has been exceeded. As in:
class DelayedImpl<T> implements Delayed {
private Future<T> task;
private final long maxExecTimeMinutes = MAX_THREAD_LIFE_MINUTES;
private final long startInMillis = System.currentTimeMillis();
private DelayedImpl(Future<T> task) {
this.task = task;
}
public long getDelay(TimeUnit unit) {
return unit.convert((startInMillis + maxExecTimeMinutes*60*1000) - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
}
public int compareTo(Delayed o) {
Long thisDelay = getDelay(TimeUnit.MILLISECONDS);
Long thatDelay = o.getDelay(TimeUnit.MILLISECONDS);
return thisDelay.compareTo(thatDelay);
}
public Future<T> getTask() {
return task;
}
}