1

Assume I have a scheduler

@Component
public class Scheduler{

    private static int counter = 0;

    private synchronized void countIt(){
        counter++;
    }

    @Scheduled(fixedDelay = 3000)
    public void job1(){
        countIt();
    }

    @Scheduled(fixedDelay = 6000)
    public void job2(){
        countIt();
    }
}

Different task trigger in different case will call countIt.

When two or more job call countIt simultaneous, it will cause starvation.

Could any one tell me if there is a way to avoid this situation?

Roy
  • 65
  • 1
  • 7
  • 3
    does not look like a case for deadlock – AdamSkywalker Oct 14 '16 at 12:12
  • @AdamSkywalker the real case is a little complicated. I have lots of threads call this synchronized method. When they call the method in the same time, deadlock happened. – Roy Oct 14 '16 at 12:17
  • 2
    deadlock is a situation when thread 1 holds resource A and needs resource B, and thread 2 holds resource B and needs resource A. synchronized method is a mutex, alone it can't cause a deadlock – AdamSkywalker Oct 14 '16 at 12:21
  • 1
    maybe your thread got stuck inside a method and other threads are waiting for it, but it's not a deadlock – AdamSkywalker Oct 14 '16 at 12:22
  • At the most, this could cause starvation, but not a deadlock. – Haroldo_OK Oct 14 '16 at 12:30
  • @AdamSkywalker I think I use a wrong word, as Haroldo_OK figure out, it is starvation. – Roy Oct 14 '16 at 12:41

2 Answers2

0

This should not deadlock.

A Deadlock is caused by one thread locking resource A and then attempting to lock resource B while another thread locks resource B and then tries to lock resource A. There are more complex ways a deadlock can occurr but deadlocks cannot happen with only one lock.

In your case there is only one lock so there is no deadlock.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
0

There is no deadlock here!

Use ReetrantLock with Fair policy. if u dont know ReentrantLock please google it.

private final ReentrantLock lock = new ReentrantLock(true);
Ugur Tufekci
  • 350
  • 2
  • 13