squid:S2276 incorrectly flags Thread.sleep in lambda


(Magnus Reftel) #1

Hi,

the rule squid:S2276 incorrectly flags usages of Thread.sleep in lambdas inside synchronized methods as if they were called with the lock held. See testcase below.This behaviour is present both in versions 7.6 and 6.2.

package com.reftel.magnus.sqsynchtest;

import java.util.concurrent.Semaphore;
import java.util.function.Consumer;
import java.util.logging.Logger;

public class Testcase
{
	private static final Logger LOGGER = Logger.getLogger("com.reftel.magnus.sqsynchtest");

	public synchronized Consumer<Semaphore> get() {
		return s -> {
			LOGGER.info("About to wait");
			s.release();
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
				throw new IllegalStateException(e);
			}
			LOGGER.info("Done waiting");
		};
	}

	public synchronized void print() {
		LOGGER.info("Running print()");
	}

	public static void main(String[] args) throws Exception {
		Testcase a = new Testcase();
		Semaphore s = new Semaphore(0);
		Consumer<Semaphore> c = a.get();
		Thread t = new Thread(() -> c.accept(s));
		t.start();
		s.acquire();
		a.print();
		t.join();
	}
}