javaspringmultithreadingdeadlockstarvation

Spring Scheduler synchronized method starvation


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?


Solution

  • 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);