Skip to content

Thread Suspend Resume

Neither "Thread.Resume" nor "Thread.Suspend" should be used

What does this mean ?

Thread.Suspend and Thread.Resume can give unpredictable results, and both methods have been deprecated.

What can happen ?

If Thread.Suspend is not used very carefully, a thread can be suspended while holding a lock, thus leading to a deadlock.

Recommendation

Other safer synchronization mechanisms should be used, such as Monitor, Mutex, and Semaphore.

Sample Code

Vulnerable :

static void Main(string[] args)
{
  // ...
  Thread.CurrentThread.Suspend(); // Noncompliant
  Thread.CurrentThread.Resume(); // Noncompliant
}

Non Vulnerable :

ThreadFactory threadFactory = Executors.defaultThreadFactory();
ThreadPoolExecutor executorPool = new ThreadPoolExecutor(3, 10, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2), threadFactory);

for (int i = 0; i < 10; i++) {
  executorPool.execute(new JobThread("Job: " + i));
}

System.out.println(executorPool.getActiveCount()); // Compliant
executorPool.shutdown();

References :