nus-yam/ex-repair huggingface dataset:
Program: 161663
Project: 161663
Buggy source:
/** 
 * This adds a log message to the stored log.  Keep in mind this will continue to consume more  and more memory until   {@link #getAllStoredMessages()} is called.
 * @param msg message to be stored into log map
 */
public static void log(String msg){
  long startTime=Clock.systemNanoTime();
  long time=startTime;
  String replacement=logMap.putIfAbsent(time,msg);
  while (replacement != null) {
    replacement=logMap.putIfAbsent(++time,msg);
  }
}

Fixed version (ground truth):
/** 
 * This adds a log message to the stored log.  Keep in mind this will continue to consume more  and more memory until   {@link #getAllStoredMessages()} is called.
 * @param msg message to be stored into log map
 */
public static void log(String msg){
  long startTime=Clock.accurateNanoTime();
  long time=startTime;
  String replacement=logMap.putIfAbsent(time,msg);
  while (replacement != null) {
    replacement=logMap.putIfAbsent(++time,msg);
  }
}
Program: 161665
Project: 161665
Buggy source:
@Override public boolean cancel(boolean interruptThread){
  if (done.get()) {
    return false;
  }
  Thread localThread=runningThread;
  if (setDone()) {
    this.canceled=true;
    if (interruptThread) {
      if (localThread != null) {
        localThread.interrupt();
      }
    }
    listenerHelper.callListeners();
    return true;
  }
 else {
    return false;
  }
}

Fixed version (ground truth):
@Override public boolean cancel(boolean interruptThread){
  Thread localThread=runningThread;
  if (setDone()) {
    this.canceled=true;
    if (interruptThread) {
      if (localThread != null) {
        localThread.interrupt();
      }
    }
synchronized (resultLock) {
      resultLock.notifyAll();
    }
    listenerHelper.callListeners();
    return true;
  }
 else {
    return false;
  }
}
Program: 161666
Project: 161666
Buggy source:
/** 
 * Call to indicate this future is done, and provide the given result.  It is expected that only  this or   {@link #setFailure(Throwable)} are called.If future has already completed and constructed with  {@link #SettableListenableFuture()} or {@code true} provided to {@link #SettableListenableFuture(boolean)} this will throw an {@link IllegalStateException}.  If complete but constructed with a   {@code false} this result will be ignored.
 * @param result result to provide for {@link #get()} call, can be {@code null}
 * @return {@code true} if the result was set (ie future did not complete in failure or cancel}
 */
public boolean setResult(T result){
  if (!setDone()) {
    return false;
  }
  this.result=result;
  listenerHelper.callListeners();
  return true;
}

Fixed version (ground truth):
/** 
 * Call to indicate this future is done, and provide the given result.  It is expected that only  this or   {@link #setFailure(Throwable)} are called.If future has already completed and constructed with  {@link #SettableListenableFuture()} or {@code true} provided to {@link #SettableListenableFuture(boolean)} this will throw an {@link IllegalStateException}.  If complete but constructed with a   {@code false} this result will be ignored.
 * @param result result to provide for {@link #get()} call, can be {@code null}
 * @return {@code true} if the result was set (ie future did not complete in failure or cancel}
 */
public boolean setResult(T result){
  if (setDone()) {
    this.result=result;
synchronized (resultLock) {
      resultLock.notifyAll();
    }
    listenerHelper.callListeners();
    return true;
  }
  return false;
}
Program: 161667
Project: 161667
Buggy source:
private boolean setDone(){
  if (done.compareAndSet(false,true)) {
    runningThread=null;
synchronized (resultLock) {
      resultLock.notifyAll();
    }
    return true;
  }
 else {
    if (throwIfAlreadyComplete) {
      throw new IllegalStateException("String_Node_Str");
    }
    return false;
  }
}

Fixed version (ground truth):
private boolean setDone(){
  if (done.compareAndSet(false,true)) {
    runningThread=null;
    return true;
  }
 else {
    if (throwIfAlreadyComplete) {
      throw new IllegalStateException("String_Node_Str");
    }
    return false;
  }
}
Program: 161668
Project: 161668
Buggy source:
/** 
 * Call to indicate this future is done, and provide the occurred failure.  It is expected that  only this or   {@link #setResult(Object)} are called, and only called once.  If the provided failure is  {@code null}, a new   {@link Exception} will be created so that something is always provided in the  {@link ExecutionException} on calls to {@link #get()}. If future has already completed and constructed with   {@link #SettableListenableFuture()} or {@code true} provided to {@link #SettableListenableFuture(boolean)} this will throw an {@link IllegalStateException}.  If complete but constructed with a   {@code false} this failure result will be ignored.
 * @param failure Throwable that caused failure during computation.
 * @return {@code true} if the failure was set (ie future did not complete with result or cancel}
 */
public boolean setFailure(Throwable failure){
  if (!setDone()) {
    return false;
  }
  if (failure == null) {
    failure=new Exception();
  }
  this.failure=failure;
  listenerHelper.callListeners();
  return true;
}

Fixed version (ground truth):
/** 
 * Call to indicate this future is done, and provide the occurred failure.  It is expected that  only this or   {@link #setResult(Object)} are called, and only called once.  If the provided failure is  {@code null}, a new   {@link Exception} will be created so that something is always provided in the  {@link ExecutionException} on calls to {@link #get()}. If future has already completed and constructed with   {@link #SettableListenableFuture()} or {@code true} provided to {@link #SettableListenableFuture(boolean)} this will throw an {@link IllegalStateException}.  If complete but constructed with a   {@code false} this failure result will be ignored.
 * @param failure Throwable that caused failure during computation.
 * @return {@code true} if the failure was set (ie future did not complete with result or cancel}
 */
public boolean setFailure(Throwable failure){
  if (setDone()) {
    if (failure == null) {
      failure=new Exception();
    }
    this.failure=failure;
synchronized (resultLock) {
      resultLock.notifyAll();
    }
    listenerHelper.callListeners();
    return true;
  }
  return false;
}
Program: 161669
Project: 161669
Buggy source:
/** 
 * Call to calculate how many milliseconds until the provided time.  If we are past the  provided hour/minute, it will be the milliseconds until we reach that time with the NEXT day.   Because of use of   {@link Clock#lastKnownTimeMillis()}, this calculation will only be accurate  within about 100 milliseconds.  Of course if provided to a scheduler, depending on it's work  load that variation may be greater.
 * @param now Current time in milliseconds since epoc
 * @param hour Hour in the 24 hour format, can not be negative and must be less than 24
 * @param minute Minute to calculate too, can not be negative and must be less than 60
 * @return Time in milliseconds till provided time is reached
 */
protected static long getDelayTillHour(long now,int hour,int minute){
  long delayInMillis=TimeUnit.MINUTES.toMillis(minute);
  long currentHour=TimeUnit.MILLISECONDS.toHours(now % TimeUnit.DAYS.toMillis(1));
  if (hour > currentHour) {
    delayInMillis+=TimeUnit.HOURS.toMillis(hour - currentHour);
  }
 else   if (hour < currentHour) {
    delayInMillis+=TimeUnit.HOURS.toMillis(TimeUnit.DAYS.toHours(1) - currentHour + hour);
  }
 else {
    return getDelayTillMinute(Clock.lastKnownTimeMillis(),minute);
  }
  long offset=now % TimeUnit.HOURS.toMillis(1);
  return delayInMillis - offset;
}

Fixed version (ground truth):
/** 
 * Call to calculate how many milliseconds until the provided time.  If we are past the  provided hour/minute, it will be the milliseconds until we reach that time with the NEXT day.   Because of use of   {@link Clock#lastKnownTimeMillis()}, this calculation will only be accurate  within about 100 milliseconds.  Of course if provided to a scheduler, depending on it's work  load that variation may be greater.
 * @param now Current time in milliseconds since epoc
 * @param hour Hour in the 24 hour format, can not be negative and must be less than 24
 * @param minute Minute to calculate too, can not be negative and must be less than 60
 * @return Time in milliseconds till provided time is reached
 */
protected static long getDelayTillHour(long now,int hour,int minute){
  long delayInMillis=TimeUnit.MINUTES.toMillis(minute);
  long currentHour=TimeUnit.MILLISECONDS.toHours(now % TimeUnit.DAYS.toMillis(1));
  if (hour > currentHour) {
    delayInMillis+=TimeUnit.HOURS.toMillis(hour - currentHour);
  }
 else   if (hour < currentHour) {
    delayInMillis+=TimeUnit.HOURS.toMillis(TimeUnit.DAYS.toHours(1) - currentHour + hour);
  }
 else {
    long result=getDelayTillMinute(Clock.lastKnownTimeMillis(),minute);
    if (TimeUnit.MILLISECONDS.toMinutes(result) <= minute) {
      return result;
    }
 else {
      return result + TimeUnit.HOURS.toMillis(TimeUnit.DAYS.toHours(1) - 1);
    }
  }
  long offset=now % TimeUnit.HOURS.toMillis(1);
  return delayInMillis - offset;
}
Program: 161670
Project: 161670
Buggy source:
/** 
 * Call to check if the service has been started, and not shutdown yet.
 * @return {@code true} if the service is currently running
 */
public boolean isRunning(){
  return state.get() == 1;
}

Fixed version (ground truth):
/** 
 * Call to check if the service has been started, and not shutdown yet.  If you need a check  that will be consistent while both new and while running please see   {@link #hasBeenStopped()}.
 * @return {@code true} if the service is currently running
 */
public boolean isRunning(){
  return state.get() == 1;
}
Program: 161671
Project: 161671
Buggy source:
/** 
 * Finishes shutdown process, and clears any tasks that remain in the queue.
 * @return a list of runnables which remained in the queue after shutdown
 */
private List<Runnable> finishShutdown(){
  shutdownFinished=true;
  scheduler.cancelTick();
  return scheduler.clearTasks();
}

Fixed version (ground truth):
/** 
 * Finishes shutdown process, and clears any tasks that remain in the queue.
 * @return a list of runnables which remained in the queue after shutdown
 */
private List<Runnable> finishShutdown(){
  state.set(2);
  scheduler.cancelTick();
  return scheduler.clearTasks();
}
Program: 161672
Project: 161672
Buggy source:
/** 
 * Gets the instance of the scheduler for this instance.  The scheduler must be accessed from  this function because it is lazily constructed and started.  This call will verify the  scheduler is running before it is returned
 * @return instance of the internal scheduler
 * @throws RejectedExecutionException thrown if the scheduler has been shutdown
 */
protected NoThreadScheduler getRunningScheduler() throws RejectedExecutionException {
  SchedulerManager result=getSchedulerManager();
  if (!result.isRunning()) {
    throw new RejectedExecutionException("String_Node_Str");
  }
  return result.scheduler;
}

Fixed version (ground truth):
/** 
 * Gets the instance of the scheduler for this instance.  The scheduler must be accessed from  this function because it is lazily constructed and started.  This call will verify the  scheduler is running before it is returned
 * @return instance of the internal scheduler
 * @throws RejectedExecutionException thrown if the scheduler has been shutdown
 */
protected NoThreadScheduler getRunningScheduler() throws RejectedExecutionException {
  SchedulerManager result=getSchedulerManager();
  if (result.hasBeenStopped()) {
    throw new RejectedExecutionException("String_Node_Str");
  }
  return result.scheduler;
}
Program: 161673
Project: 161673
Buggy source:
@Override public void run(){
  while (!shutdownFinished) {
    try {
      scheduler.tick(null);
    }
 catch (    InterruptedException e) {
      Thread.interrupted();
    }
catch (    Throwable t) {
      ExceptionUtils.handleException(t);
    }
  }
}

Fixed version (ground truth):
@Override public void run(){
  while (state.get() != 2) {
    try {
      scheduler.tick(null);
    }
 catch (    InterruptedException e) {
      Thread.interrupted();
    }
catch (    Throwable t) {
      ExceptionUtils.handleException(t);
    }
  }
}
Program: 161674
Project: 161674
Buggy source:
protected SchedulerManager(ThreadFactory threadFactory){
  scheduler=new NoThreadScheduler(true);
  execThread=threadFactory.newThread(this);
  if (execThread.isAlive()) {
    throw new IllegalThreadStateException();
  }
  shutdownFinished=false;
}

Fixed version (ground truth):
public SchedulerManager(ThreadFactory threadFactory){
  scheduler=new NoThreadScheduler(true);
  execThread=threadFactory.newThread(this);
  if (execThread.isAlive()) {
    throw new IllegalThreadStateException();
  }
}
Program: 161675
Project: 161675
Buggy source:
/** 
 * Call to stop the thread which is running tasks.  If this has already been stopped this call  will have no effect.  Regardless if true or false is passed in, running tasks will NOT be  Interrupted or stopped.  True will only prevent ANY extra tasks from running, while a false  will let tasks ready to run complete before shutting down.
 * @param stopImmediately {@code false} if the scheduler should let ready tasks run, {@code true} stops scheduler immediately
 * @return if {@code stopImmediately} is {@code true}, this will include tasks which were queued to run,  otherwise will be an empty list
 */
protected List<Runnable> stop(boolean stopImmediately){
  if (stopIfRunning()) {
    if (stopImmediately) {
      return finishShutdown();
    }
 else {
      scheduler.execute(new Runnable(){
        @Override public void run(){
          finishShutdown();
        }
      }
);
    }
  }
  return Collections.emptyList();
}

Fixed version (ground truth):
/** 
 * Call to stop the thread which is running tasks.  If this has already been stopped this call  will have no effect.  Regardless if true or false is passed in, running tasks will NOT be  Interrupted or stopped.  True will only prevent ANY extra tasks from running, while a false  will let tasks ready to run complete before shutting down.
 * @param stopImmediately {@code false} if the scheduler should let ready tasks run, {@code true} stops scheduler immediately
 * @return if {@code stopImmediately} is {@code true}, this will include tasks which were queued to run,  otherwise will be an empty list
 */
public List<Runnable> stop(boolean stopImmediately){
  int stateVal=state.get();
  while (stateVal < 1) {
    if (state.compareAndSet(stateVal,1)) {
      if (stopImmediately || stateVal == -1) {
        return finishShutdown();
      }
 else {
        scheduler.execute(new Runnable(){
          @Override public void run(){
            finishShutdown();
          }
        }
);
      }
      break;
    }
 else {
      stateVal=state.get();
    }
  }
  return Collections.emptyList();
}
Program: 161676
Project: 161676
Buggy source:
@Override public boolean isShutdown(){
  SchedulerManager sm=sManager.get();
  if (sm != null) {
    return !sm.isRunning();
  }
 else {
    return false;
  }
}

Fixed version (ground truth):
@Override public boolean isShutdown(){
  SchedulerManager sm=sManager.get();
  if (sm != null) {
    return sm.hasBeenStopped();
  }
 else {
    return false;
  }
}
Program: 161677
Project: 161677
Buggy source:
@Override public boolean isTerminated(){
  SchedulerManager sm=singleThreadScheduler.sManager.get();
  if (sm == null || sm.isRunning()) {
    return false;
  }
 else {
    return !sm.execThread.isAlive();
  }
}

Fixed version (ground truth):
@Override public boolean isTerminated(){
  SchedulerManager sm=singleThreadScheduler.sManager.get();
  if (sm == null || !sm.hasBeenStopped()) {
    return false;
  }
 else {
    return !sm.execThread.isAlive();
  }
}
Program: 161678
Project: 161678
Buggy source:
/** 
 * Getter for the currently set keep alive time.
 * @return current keep alive time
 */
public long getKeepAliveTime(){
  return keepAliveTimeInMs;
}

Fixed version (ground truth):
/** 
 * Getter for the currently set worker keep alive time.
 * @return current keep alive time
 */
public long getKeepAliveTime(){
  return keepAliveTimeInMs;
}
Program: 161679
Project: 161679
Buggy source:
@Override public void run(){
  shutdownNow();
}

Fixed version (ground truth):
@Override public void run(){
  lowPriorityConsumer.stopAndDrainQueueInto(null);
  highPriorityConsumer.stopAndDrainQueueInto(null);
  wm.finishShutdown();
}
Program: 161680
Project: 161680
Buggy source:
@Override public void executing(){
  if (canceled) {
    return;
  }
  executing=true;
switch (priority) {
case High:
    highPriorityConsumer.addScheduledLast(this);
  break;
case Low:
lowPriorityConsumer.addScheduledLast(this);
break;
default :
throw new UnsupportedOperationException();
}
}

Fixed version (ground truth):
@Override public void executing(){
  if (canceled) {
    return;
  }
  executing=true;
  queueManager.addScheduledLast(this);
}
Program: 161681
Project: 161681
Buggy source:
/** 
 * After a task has been pulled from the queue and is ready to execute it is provided here.   This function will get an available worker (or create one if necessary and possible), and  then provide the task to that available worker.
 * @param task Task to execute once we have an available worker
 * @throws InterruptedException Thrown if thread is interrupted while waiting for a worker
 */
protected void runHighPriorityTask(TaskWrapper task) throws InterruptedException {
  Worker w=null;
synchronized (workersLock) {
    if (!shutdownFinishing) {
      if (currentPoolSize >= maxPoolSize) {
        lastHighDelay=task.getDelayEstimateInMillis();
        w=getExistingWorker(Long.MAX_VALUE);
      }
 else {
        lastHighDelay=0;
        if (availableWorkers.isEmpty()) {
          w=makeNewWorker();
        }
 else {
          w=availableWorkers.removeFirst();
        }
      }
    }
  }
  if (w != null) {
    w.nextTask(task);
  }
}

Fixed version (ground truth):
/** 
 * After a task has been pulled from the queue and is ready to execute it is provided here.   This function will get an available worker (or create one if necessary and possible), and  then provide the task to that available worker.
 * @param task Task to execute once we have an available worker
 * @throws InterruptedException Thrown if thread is interrupted while waiting for a worker
 */
protected void runHighPriorityTask(TaskWrapper task) throws InterruptedException {
  Worker w=null;
synchronized (workersLock) {
    if (!shutdownFinishing) {
      if (currentPoolSize >= maxPoolSize) {
        lastHighDelayMillis=task.getDelayEstimateInMs();
        w=getExistingWorker(Long.MAX_VALUE);
        lastHighDelayMillis=task.getDelayEstimateInMs();
      }
 else {
        lastHighDelayMillis=0;
        if (availableWorkers.isEmpty()) {
          w=makeNewWorker();
        }
 else {
          w=availableWorkers.removeFirst();
        }
      }
    }
  }
  if (w != null) {
    w.nextTask(task);
  }
}
Program: 161682
Project: 161682
Buggy source:
/** 
 * Call to check how many tasks are currently being executed in this thread pool.
 * @return current number of running tasks
 */
public int getCurrentRunningCount(){
synchronized (workersLock) {
    return currentPoolSize - availableWorkers.size();
  }
}

Fixed version (ground truth):
/** 
 * Call to check how many workers are currently executing tasks.
 * @return current number of workers executing tasks
 */
public int getCurrentRunningCount(){
synchronized (workersLock) {
    return currentPoolSize - availableWorkers.size();
  }
}
Program: 161683
Project: 161683
Buggy source:
@Override public void scheduleAtFixedRate(Runnable task,long initialDelay,long period,TaskPriority priority){
  ArgumentVerifier.assertNotNull(task,"String_Node_Str");
  ArgumentVerifier.assertNotNegative(initialDelay,"String_Node_Str");
  ArgumentVerifier.assertGreaterThanZero(period,"String_Node_Str");
  if (priority == null) {
    priority=defaultPriority;
  }
  addToScheduleQueue(new RecurringRateTaskWrapper(task,priority,initialDelay,period));
}

Fixed version (ground truth):
@Override public void scheduleAtFixedRate(Runnable task,long initialDelay,long period,TaskPriority priority){
  ArgumentVerifier.assertNotNull(task,"String_Node_Str");
  ArgumentVerifier.assertNotNegative(initialDelay,"String_Node_Str");
  ArgumentVerifier.assertGreaterThanZero(period,"String_Node_Str");
  if (priority == null) {
    priority=defaultPriority;
  }
  addToScheduleQueue(priority,new RecurringRateTaskWrapper(task,getQueueManager(priority),initialDelay,period));
}
Program: 161684
Project: 161684
Buggy source:
public TaskWrapper(Runnable task,TaskPriority priority){
  this.priority=priority;
  this.task=task;
  canceled=false;
}

Fixed version (ground truth):
public TaskWrapper(Runnable task){
  this.task=task;
  canceled=false;
}
Program: 161685
Project: 161685
Buggy source:
protected RecurringRateTaskWrapper(Runnable task,TaskPriority priority,long initialDelay,long period){
  super(task,priority,initialDelay);
  this.period=period;
}

Fixed version (ground truth):
protected RecurringRateTaskWrapper(Runnable task,QueueManager queueManager,long initialDelay,long period){
  super(task,queueManager,initialDelay);
  this.period=period;
}
Program: 161687
Project: 161687
Buggy source:
/** 
 * Returns a count of how many tasks are either waiting to be executed, or are scheduled to be  executed at a future point for a specific priority.
 * @param priority priority for tasks to be counted
 * @return quantity of tasks waiting execution or scheduled to be executed later
 */
public int getScheduledTaskCount(TaskPriority priority){
  if (priority == null) {
    return getScheduledTaskCount();
  }
switch (priority) {
case High:
    return highPriorityConsumer.queueSize();
case Low:
  return lowPriorityConsumer.queueSize();
default :
throw new UnsupportedOperationException();
}
}

Fixed version (ground truth):
/** 
 * Returns a count of how many tasks are either waiting to be executed, or are scheduled to be  executed at a future point for a specific priority.
 * @param priority priority for tasks to be counted
 * @return quantity of tasks waiting execution or scheduled to be executed later
 */
public int getScheduledTaskCount(TaskPriority priority){
  if (priority == null) {
    return getScheduledTaskCount();
  }
  return getQueueManager(priority).queueSize();
}
Program: 161688
Project: 161688
Buggy source:
protected RecurringDelayTaskWrapper(Runnable task,TaskPriority priority,long initialDelay,long recurringDelay){
  super(task,priority,initialDelay);
  this.recurringDelay=recurringDelay;
}

Fixed version (ground truth):
protected RecurringDelayTaskWrapper(Runnable task,QueueManager queueManager,long initialDelay,long recurringDelay){
  super(task,queueManager,initialDelay);
  this.recurringDelay=recurringDelay;
}
Program: 161689
Project: 161689
Buggy source:
public QueueManager(ThreadFactory threadFactory,String threadName){
  this.threadFactory=threadFactory;
  this.threadName=threadName;
  this.executeQueue=new ConcurrentLinkedQueue<OneTimeTaskWrapper>();
  this.scheduleQueue=new ConcurrentArrayList<TaskWrapper>(QUEUE_FRONT_PADDING,QUEUE_REAR_PADDING);
  runningThread=null;
}

Fixed version (ground truth):
public QueueManager(WorkerPool workerPool,TaskPriority queuePriority,String threadName){
  this.workerPool=workerPool;
  this.threadName=threadName;
  this.executeQueue=new ConcurrentLinkedQueue<OneTimeTaskWrapper>();
  this.scheduleQueue=new ConcurrentArrayList<TaskWrapper>(QUEUE_FRONT_PADDING,QUEUE_REAR_PADDING);
  this.queuePriority=queuePriority;
  runningThread=null;
}
Program: 161690
Project: 161690
Buggy source:
/** 
 * Stops any new tasks from being submitted to the pool.  But allows all tasks which are  submitted to execute, or scheduled (and have elapsed their delay time) to run.  If recurring  tasks are present they will also be unable to reschedule.  If   {@code shutdown()} or {@link #shutdownNow()} has already been called, this will have no effect.  If you wish to not want to run any queued tasks you should use  {@link #shutdownNow()}.
 */
public void shutdown(){
  if (!shutdownStarted.getAndSet(true)) {
    highPriorityConsumer.addExecute(new OneTimeTaskWrapper(new ShutdownRunnable(),TaskPriority.High,1));
  }
}

Fixed version (ground truth):
/** 
 * Stops any new tasks from being submitted to the pool.  But allows all tasks which are  submitted to execute, or scheduled (and have elapsed their delay time) to run.  If recurring  tasks are present they will also be unable to reschedule.  If   {@code shutdown()} or {@link #shutdownNow()} has already been called, this will have no effect.  If you wish to not want to run any queued tasks you should use  {@link #shutdownNow()}.
 */
public void shutdown(){
  if (workerPool.startShutdown()) {
    ShutdownRunnable sr=new ShutdownRunnable(workerPool,lowPriorityConsumer,highPriorityConsumer);
    highPriorityConsumer.addExecute(new OneTimeTaskWrapper(sr,1));
  }
}
Program: 161691
Project: 161691
Buggy source:
/** 
 * Change the set idle thread keep alive time.  If this is a reduction in the previously set  keep alive time, this call will then check for expired worker threads.
 * @param keepAliveTimeInMs New keep alive time in milliseconds
 */
public void setKeepAliveTime(long keepAliveTimeInMs){
  ArgumentVerifier.assertNotNegative(keepAliveTimeInMs,"String_Node_Str");
  boolean checkForExpiredWorkers=this.keepAliveTimeInMs > keepAliveTimeInMs;
  this.keepAliveTimeInMs=keepAliveTimeInMs;
  if (checkForExpiredWorkers) {
synchronized (workersLock) {
      expireOldWorkers();
    }
  }
}

Fixed version (ground truth):
/** 
 * Change the set idle worker keep alive time.  If this is a reduction in the previously set  keep alive time, this call will then check for expired workers.
 * @param keepAliveTimeInMs New keep alive time in milliseconds
 */
public void setKeepAliveTime(long keepAliveTimeInMs){
  ArgumentVerifier.assertNotNegative(keepAliveTimeInMs,"String_Node_Str");
  boolean checkForExpiredWorkers=this.keepAliveTimeInMs > keepAliveTimeInMs;
  this.keepAliveTimeInMs=keepAliveTimeInMs;
  if (checkForExpiredWorkers) {
synchronized (workersLock) {
      expireOldWorkers();
    }
  }
}
Program: 161692
Project: 161692
Buggy source:
@Override public boolean isShutdown(){
  return shutdownStarted.get();
}

Fixed version (ground truth):
@Override public boolean isShutdown(){
  return workerPool.isShutdownStarted();
}
Program: 161693
Project: 161693
Buggy source:
/** 
 * Adds the ready TaskWrapper to the correct schedule queue.  Using the priority specified in the  task, we pick the correct queue and add it. If this is just a single execution with no delay use   {@link #addToExecuteQueue(OneTimeTaskWrapper)}.
 * @param task {@link TaskWrapper} to queue for the scheduler
 */
protected void addToScheduleQueue(TaskWrapper task){
  if (shutdownStarted.get()) {
    throw new RejectedExecutionException("String_Node_Str");
  }
switch (task.priority) {
case High:
    highPriorityConsumer.addScheduled(task);
  break;
case Low:
lowPriorityConsumer.addScheduled(task);
break;
default :
throw new UnsupportedOperationException();
}
}

Fixed version (ground truth):
/** 
 * Adds the ready TaskWrapper to the correct schedule queue.  Using the priority specified in the  task, we pick the correct queue and add it. If this is just a single execution with no delay use   {@link #addToExecuteQueue(OneTimeTaskWrapper)}.
 * @param task {@link TaskWrapper} to queue for the scheduler
 */
protected void addToScheduleQueue(TaskPriority priority,TaskWrapper task){
  if (workerPool.isShutdownStarted()) {
    throw new RejectedExecutionException("String_Node_Str");
  }
  getQueueManager(priority).addScheduled(task);
}
Program: 161694
Project: 161694
Buggy source:
protected RecurringTaskWrapper(Runnable task,TaskPriority priority,long initialDelay){
  super(task,priority);
  executing=false;
  this.nextRunTime=Clock.accurateForwardProgressingMillis() + initialDelay;
}

Fixed version (ground truth):
protected RecurringTaskWrapper(Runnable task,QueueManager queueManager,long initialDelay){
  super(task);
  this.queueManager=queueManager;
  executing=false;
  this.nextRunTime=Clock.accurateForwardProgressingMillis() + initialDelay;
}
Program: 161695
Project: 161695
Buggy source:
@Override public void scheduleWithFixedDelay(Runnable task,long initialDelay,long recurringDelay,TaskPriority priority){
  ArgumentVerifier.assertNotNull(task,"String_Node_Str");
  ArgumentVerifier.assertNotNegative(initialDelay,"String_Node_Str");
  ArgumentVerifier.assertNotNegative(recurringDelay,"String_Node_Str");
  if (priority == null) {
    priority=defaultPriority;
  }
  addToScheduleQueue(new RecurringDelayTaskWrapper(task,priority,initialDelay,recurringDelay));
}

Fixed version (ground truth):
@Override public void scheduleWithFixedDelay(Runnable task,long initialDelay,long recurringDelay,TaskPriority priority){
  ArgumentVerifier.assertNotNull(task,"String_Node_Str");
  ArgumentVerifier.assertNotNegative(initialDelay,"String_Node_Str");
  ArgumentVerifier.assertNotNegative(recurringDelay,"String_Node_Str");
  if (priority == null) {
    priority=defaultPriority;
  }
  addToScheduleQueue(priority,new RecurringDelayTaskWrapper(task,getQueueManager(priority),initialDelay,recurringDelay));
}
Program: 161696
Project: 161696
Buggy source:
/** 
 * Constructs a new thread pool, though no threads will be started till it accepts it's first  request.  This provides the extra parameters to tune what tasks submitted without a priority  will be scheduled as.  As well as the maximum wait for low priority tasks.  The longer low  priority tasks wait for a worker, the less chance they will have to make a thread.  But it  also makes low priority tasks execution time less predictable.
 * @param corePoolSize pool size that should be maintained
 * @param maxPoolSize maximum allowed thread count
 * @param keepAliveTimeInMs time to wait for a given thread to be idle before killing
 * @param defaultPriority priority to give tasks which do not specify it
 * @param maxWaitForLowPriorityInMs time low priority tasks wait for a worker
 * @param threadFactory thread factory for producing new threads within executor
 */
public PriorityScheduler(int corePoolSize,int maxPoolSize,long keepAliveTimeInMs,TaskPriority defaultPriority,long maxWaitForLowPriorityInMs,ThreadFactory threadFactory){
  ArgumentVerifier.assertGreaterThanZero(corePoolSize,"String_Node_Str");
  if (maxPoolSize < corePoolSize) {
    throw new IllegalArgumentException("String_Node_Str");
  }
  setKeepAliveTime(keepAliveTimeInMs);
  setMaxWaitForLowPriority(maxWaitForLowPriorityInMs);
  if (defaultPriority == null) {
    defaultPriority=DEFAULT_PRIORITY;
  }
  if (threadFactory == null) {
    threadFactory=new ConfigurableThreadFactory(PriorityScheduler.class.getSimpleName() + "String_Node_Str",true);
  }
  this.defaultPriority=defaultPriority;
  workersLock=new Object();
  poolSizeChangeLock=new Object();
  availableWorkers=new ArrayDeque<Worker>(corePoolSize);
  this.threadFactory=threadFactory;
  highPriorityConsumer=new QueueManager(threadFactory,TaskPriority.High + QUEUE_CONSUMER_THREAD_NAME_SUFFIX);
  lowPriorityConsumer=new QueueManager(threadFactory,TaskPriority.Low + QUEUE_CONSUMER_THREAD_NAME_SUFFIX);
  shutdownStarted=new AtomicBoolean(false);
  shutdownFinishing=false;
  this.corePoolSize=corePoolSize;
  this.maxPoolSize=maxPoolSize;
  this.allowCorePoolTimeout=false;
  this.lastHighDelay=0;
  waitingForWorkerCount=0;
  currentPoolSize=0;
}

Fixed version (ground truth):
/** 
 * This constructor is designed for extending classes to be able to provide their own  implementation of   {@link WorkerPool}.  Ultimately all constructors will defer to this one.
 * @param workerPool WorkerPool to handle accepting tasks and providing them to a worker for execution
 * @param defaultPriority Default priority to store in case no priority is provided for tasks
 */
protected PriorityScheduler(WorkerPool workerPool,TaskPriority defaultPriority){
  if (defaultPriority == null) {
    defaultPriority=DEFAULT_PRIORITY;
  }
  this.workerPool=workerPool;
  this.defaultPriority=defaultPriority;
  highPriorityConsumer=new QueueManager(workerPool,TaskPriority.High,TaskPriority.High + QUEUE_CONSUMER_THREAD_NAME_SUFFIX);
  lowPriorityConsumer=new QueueManager(workerPool,TaskPriority.Low,TaskPriority.Low + QUEUE_CONSUMER_THREAD_NAME_SUFFIX);
}
Program: 161697
Project: 161697
Buggy source:
private void clearQueue(Collection<? extends TaskWrapper> queue,List<Runnable> resultList){
  Iterator<? extends TaskWrapper> it=queue.iterator();
  while (it.hasNext()) {
    TaskWrapper tw=it.next();
    tw.cancel();
    if (!(tw.task instanceof ShutdownRunnable)) {
      resultList.add(tw.task);
    }
  }
  queue.clear();
}

Fixed version (ground truth):
private static void clearQueue(Collection<? extends TaskWrapper> queue,List<Runnable> resultList){
  Iterator<? extends TaskWrapper> it=queue.iterator();
  while (it.hasNext()) {
    TaskWrapper tw=it.next();
    tw.cancel();
    if (resultList != null && !(tw.task instanceof ShutdownRunnable)) {
      resultList.add(tw.task);
    }
  }
  queue.clear();
}
Program: 161698
Project: 161698
Buggy source:
/** 
 * Getter for the current set core pool size.
 * @return current core pool size
 */
public int getCorePoolSize(){
  return corePoolSize;
}

Fixed version (ground truth):
/** 
 * Getter for the current set core worker pool size.
 * @return current core pool size
 */
public int getCorePoolSize(){
  return corePoolSize;
}
Program: 161700
Project: 161700
Buggy source:
/** 
 * After the task has completed, this will reschedule the task to run again.
 */
private void reschedule(){
  updateNextRunTime();
switch (priority) {
case High:
    highPriorityConsumer.reschedule(this);
  break;
case Low:
lowPriorityConsumer.reschedule(this);
break;
default :
throw new UnsupportedOperationException();
}
executing=false;
}

Fixed version (ground truth):
/** 
 * After the task has completed, this will reschedule the task to run again.
 */
private void reschedule(){
  updateNextRunTime();
  queueManager.reschedule(this);
  executing=false;
}
Program: 161701
Project: 161701
Buggy source:
/** 
 * Checks the interrupted status of the workers thread.  If it is interrupted the status will  be cleared (unless the pool is shutting down, in which case we will gracefully shutdown the  worker).
 */
private void checkInterrupted(){
  if (Thread.interrupted()) {
    if (shutdownFinishing) {
      killWorker(this);
    }
  }
}

Fixed version (ground truth):
/** 
 * Checks the interrupted status of the workers thread.  If it is interrupted the status will  be cleared (unless the pool is shutting down, in which case we will gracefully shutdown the  worker).
 */
private void checkInterrupted(){
  if (Thread.interrupted()) {
    if (workerPool.isShutdownFinished()) {
      workerPool.killWorker(this);
    }
  }
}
Program: 161702
Project: 161702
Buggy source:
/** 
 * Makes a new   {@link PrioritySchedulerLimiter} that uses this pool as it's execution source.
 * @param maxConcurrency maximum number of threads to run in parallel in sub pool
 * @param subPoolName name to describe threads while running under this sub pool
 * @return newly created {@link PrioritySchedulerLimiter} that uses this pool as it's execution source
 */
public PrioritySchedulerInterface makeSubPool(int maxConcurrency,String subPoolName){
  if (maxConcurrency > maxPoolSize) {
    throw new IllegalArgumentException("String_Node_Str");
  }
  return new PrioritySchedulerLimiter(this,maxConcurrency,subPoolName);
}

Fixed version (ground truth):
/** 
 * Makes a new   {@link PrioritySchedulerLimiter} that uses this pool as it's execution source.
 * @param maxConcurrency maximum number of threads to run in parallel in sub pool
 * @param subPoolName name to describe threads while running under this sub pool
 * @return newly created {@link PrioritySchedulerLimiter} that uses this pool as it's execution source
 */
public PrioritySchedulerInterface makeSubPool(int maxConcurrency,String subPoolName){
  if (maxConcurrency > workerPool.getMaxPoolSize()) {
    throw new IllegalArgumentException("String_Node_Str");
  }
  return new PrioritySchedulerLimiter(this,maxConcurrency,subPoolName);
}
Program: 161703
Project: 161703
Buggy source:
/** 
 * Adds the ready TaskWrapper to the correct execute queue.  Using the priority specified in the  task, we pick the correct queue and add it. If this is a scheduled or recurring task use   {@link #addToScheduleQueue(TaskWrapper)}.
 * @param task {@link TaskWrapper} to queue for the scheduler
 */
protected void addToExecuteQueue(OneTimeTaskWrapper task){
  if (shutdownStarted.get()) {
    throw new RejectedExecutionException("String_Node_Str");
  }
switch (task.priority) {
case High:
    highPriorityConsumer.addExecute(task);
  break;
case Low:
lowPriorityConsumer.addExecute(task);
break;
default :
throw new UnsupportedOperationException();
}
}

Fixed version (ground truth):
/** 
 * Adds the ready TaskWrapper to the correct execute queue.  Using the priority specified in the  task, we pick the correct queue and add it. If this is a scheduled or recurring task use   {@link #addToScheduleQueue(TaskWrapper)}.
 * @param task {@link TaskWrapper} to queue for the scheduler
 */
protected void addToExecuteQueue(TaskPriority priority,OneTimeTaskWrapper task){
  if (workerPool.isShutdownStarted()) {
    throw new RejectedExecutionException("String_Node_Str");
  }
  getQueueManager(priority).addExecute(task);
}
Program: 161704
Project: 161704
Buggy source:
/** 
 * This function REQUIRES that workersLock is synchronized before calling.  This call creates  a new worker, starts it, but does NOT add it as an available worker (so you can immediately  use it).  If you want this worker to be available for other tasks, it must be added to the   {@code availableWorkers} queue.
 * @return Newly created worker, started and ready to accept work
 */
protected Worker makeNewWorker(){
  Worker w=new Worker();
  currentPoolSize++;
  w.start();
  return w;
}

Fixed version (ground truth):
/** 
 * This function REQUIRES that workersLock is synchronized before calling.  This call creates  a new worker, starts it, but does NOT add it as an available worker (so you can immediately  use it).  If you want this worker to be available for other tasks, it must be added to the   {@code availableWorkers} queue.
 * @return Newly created worker, started and ready to accept work
 */
protected Worker makeNewWorker(){
  Worker w=new Worker(this,threadFactory);
  currentPoolSize++;
  w.start();
  return w;
}
Program: 161705
Project: 161705
Buggy source:
/** 
 * Getter for the currently set max pool size.
 * @return current max pool size
 */
public int getMaxPoolSize(){
  return maxPoolSize;
}

Fixed version (ground truth):
/** 
 * Getter for the currently set max worker pool size.
 * @return current max pool size
 */
public int getMaxPoolSize(){
  return maxPoolSize;
}
Program: 161706
Project: 161706
Buggy source:
protected Worker(){
  thread=threadFactory.newThread(this);
  if (thread.isAlive()) {
    throw new IllegalThreadStateException();
  }
  lastRunTime=Clock.lastKnownForwardProgressingMillis();
  nextTask=null;
}

Fixed version (ground truth):
protected Worker(WorkerPool workerPool,ThreadFactory threadFactory){
  this.workerPool=workerPool;
  thread=threadFactory.newThread(this);
  if (thread.isAlive()) {
    throw new IllegalThreadStateException();
  }
  lastRunTime=Clock.lastKnownForwardProgressingMillis();
  nextTask=null;
}
Program: 161707
Project: 161707
Buggy source:
/** 
 * Stops any new tasks from being able to be executed and removes workers from the pool. This implementation refuses new submissions after this call.  And will NOT interrupt any  tasks which are currently running.  However any tasks which are waiting in queue to be run  (but have not started yet), will not be run.  Those waiting tasks will be removed, and as  workers finish with their current tasks the threads will be joined.
 * @return List of runnables which were waiting to execute
 */
public List<Runnable> shutdownNow(){
  shutdownStarted.set(true);
  shutdownAllIdleWorkers();
  List<Runnable> awaitingTasks=clearTaskQueue();
  shutdownFinishing=true;
  return awaitingTasks;
}

Fixed version (ground truth):
/** 
 * Stops any new tasks from being able to be executed and removes workers from the pool. This implementation refuses new submissions after this call.  And will NOT interrupt any  tasks which are currently running.  However any tasks which are waiting in queue to be run  (but have not started yet), will not be run.  Those waiting tasks will be removed, and as  workers finish with their current tasks the threads will be joined.
 * @return List of runnables which were waiting to execute
 */
public List<Runnable> shutdownNow(){
  workerPool.startShutdown();
  List<Runnable> awaitingTasks=clearTaskQueue();
  workerPool.finishShutdown();
  return awaitingTasks;
}
Program: 161708
Project: 161708
Buggy source:
/** 
 * Constructs a   {@link OneTimeTaskWrapper} and adds it to the most efficent queue.  If there is no delay it will use  {@link #addToExecuteQueue(OneTimeTaskWrapper)}, if there is a delay it  will be added to   {@link #addToScheduleQueue(TaskWrapper)}.
 * @param task Runnable to be executed
 * @param delayInMillis delay to wait before task is run
 * @param priority Priority for task execution
 */
protected void doSchedule(Runnable task,long delayInMillis,TaskPriority priority){
  OneTimeTaskWrapper taskWrapper=new OneTimeTaskWrapper(task,priority,delayInMillis);
  if (delayInMillis == 0) {
    addToExecuteQueue(taskWrapper);
  }
 else {
    addToScheduleQueue(taskWrapper);
  }
}

Fixed version (ground truth):
/** 
 * Constructs a   {@link OneTimeTaskWrapper} and adds it to the most efficent queue.  If there is no delay it will use  {@link #addToExecuteQueue(OneTimeTaskWrapper)}, if there is a delay it  will be added to   {@link #addToScheduleQueue(TaskWrapper)}.
 * @param task Runnable to be executed
 * @param delayInMillis delay to wait before task is run
 * @param priority Priority for task execution
 */
protected void doSchedule(Runnable task,long delayInMillis,TaskPriority priority){
  OneTimeTaskWrapper taskWrapper=new OneTimeTaskWrapper(task,delayInMillis);
  if (delayInMillis == 0) {
    addToExecuteQueue(priority,taskWrapper);
  }
 else {
    addToScheduleQueue(priority,taskWrapper);
  }
}
Program: 161709
Project: 161709
Buggy source:
protected OneTimeTaskWrapper(Runnable task,TaskPriority priority,long delay){
  super(task,priority);
  runTime=Clock.accurateForwardProgressingMillis() + delay;
}

Fixed version (ground truth):
protected OneTimeTaskWrapper(Runnable task,long delay){
  super(task);
  runTime=Clock.accurateForwardProgressingMillis() + delay;
}
Program: 161710
Project: 161710
Buggy source:
/** 
 * Ensures all core threads have been started.  This will make new idle workers to accept tasks.
 */
public void prestartAllCoreThreads(){
synchronized (workersLock) {
    boolean startedThreads=false;
    while (currentPoolSize <= corePoolSize) {
      availableWorkers.addFirst(makeNewWorker());
      startedThreads=true;
    }
    if (startedThreads) {
      workersLock.notifyAll();
    }
  }
}

Fixed version (ground truth):
/** 
 * Ensures all core threads have been started.  This will make new idle workers to accept tasks.
 */
public void prestartAllCoreThreads(){
synchronized (workersLock) {
    boolean startedThreads=false;
    while (currentPoolSize < corePoolSize) {
      availableWorkers.addFirst(makeNewWorker());
      startedThreads=true;
    }
    if (startedThreads) {
      workersLock.notifyAll();
    }
  }
}
Program: 161711
Project: 161711
Buggy source:
@Override protected ListenableScheduledFuture<?> scheduleAtFixedRate(Runnable task,long initialDelayInMillis,long periodInMillis){
  task=new ThrowableHandlingRecurringRunnable(pScheduler,task);
  ListenableRunnableFuture<Object> taskFuture=new ListenableFutureTask<Object>(true,task);
  RecurringRateTaskWrapper rrtw=pScheduler.new RecurringRateTaskWrapper(taskFuture,pScheduler.getDefaultPriority(),initialDelayInMillis,periodInMillis);
  pScheduler.addToScheduleQueue(rrtw);
  return new ScheduledFutureDelegate<Object>(taskFuture,rrtw);
}

Fixed version (ground truth):
@Override protected ListenableScheduledFuture<?> scheduleAtFixedRate(Runnable task,long initialDelayInMillis,long periodInMillis){
  task=new ThrowableHandlingRecurringRunnable(pScheduler,task);
  ListenableRunnableFuture<Object> taskFuture=new ListenableFutureTask<Object>(true,task);
  TaskPriority priority=pScheduler.getDefaultPriority();
  RecurringRateTaskWrapper rrtw=new RecurringRateTaskWrapper(taskFuture,pScheduler.getQueueManager(priority),initialDelayInMillis,periodInMillis);
  pScheduler.addToScheduleQueue(priority,rrtw);
  return new ScheduledFutureDelegate<Object>(taskFuture,rrtw);
}
Program: 161712
Project: 161712
Buggy source:
@Override protected <V>ListenableScheduledFuture<V> schedule(Callable<V> callable,long delayInMillis){
  ListenableRunnableFuture<V> taskFuture=new ListenableFutureTask<V>(false,callable);
  OneTimeTaskWrapper ottw=pScheduler.new OneTimeTaskWrapper(taskFuture,pScheduler.getDefaultPriority(),delayInMillis);
  if (delayInMillis == 0) {
    pScheduler.addToExecuteQueue(ottw);
  }
 else {
    pScheduler.addToScheduleQueue(ottw);
  }
  return new ScheduledFutureDelegate<V>(taskFuture,ottw);
}

Fixed version (ground truth):
@Override protected <V>ListenableScheduledFuture<V> schedule(Callable<V> callable,long delayInMillis){
  ListenableRunnableFuture<V> taskFuture=new ListenableFutureTask<V>(false,callable);
  OneTimeTaskWrapper ottw=new OneTimeTaskWrapper(taskFuture,delayInMillis);
  if (delayInMillis == 0) {
    pScheduler.addToExecuteQueue(pScheduler.getDefaultPriority(),ottw);
  }
 else {
    pScheduler.addToScheduleQueue(pScheduler.getDefaultPriority(),ottw);
  }
  return new ScheduledFutureDelegate<V>(taskFuture,ottw);
}
Program: 161713
Project: 161713
Buggy source:
@Override protected ListenableScheduledFuture<?> scheduleWithFixedDelay(Runnable task,long initialDelayInMs,long delayInMs){
  task=new ThrowableHandlingRecurringRunnable(scheduler,task);
  ListenableRunnableFuture<Object> taskFuture=new ListenableFutureTask<Object>(true,task);
  RecurringDelayTaskWrapper rdtw=pScheduler.new RecurringDelayTaskWrapper(taskFuture,pScheduler.getDefaultPriority(),initialDelayInMs,delayInMs);
  pScheduler.addToScheduleQueue(rdtw);
  return new ScheduledFutureDelegate<Object>(taskFuture,rdtw);
}

Fixed version (ground truth):
@Override protected ListenableScheduledFuture<?> scheduleWithFixedDelay(Runnable task,long initialDelayInMs,long delayInMs){
  task=new ThrowableHandlingRecurringRunnable(scheduler,task);
  ListenableRunnableFuture<Object> taskFuture=new ListenableFutureTask<Object>(true,task);
  TaskPriority priority=pScheduler.getDefaultPriority();
  RecurringDelayTaskWrapper rdtw=new RecurringDelayTaskWrapper(taskFuture,pScheduler.getQueueManager(priority),initialDelayInMs,delayInMs);
  pScheduler.addToScheduleQueue(priority,rdtw);
  return new ScheduledFutureDelegate<Object>(taskFuture,rdtw);
}