package ru.nsu.ccfit.bogush.factory;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class SimplePeriodical implements Periodical {
	private long period;

	private static final String LOGGER_NAME = "SimplePeriodical";
	private static final Logger logger = LogManager.getLogger(LOGGER_NAME);

	public SimplePeriodical(long period) {
		this.period = period;
	}

	private final Object lock = new Object();

	@Override
	public void setPeriod(long period) {
		logger.trace("set period " + period + " milliseconds");
		if (period < 0) {
			logger.error("period < 0");
			throw new IllegalArgumentException("period must be greater than or equal to 0");
		}
		this.period = period;
		lock.notifyAll();
	}

	@Override
	public void waitPeriod() {
		long timeToWait = period;
		while (timeToWait > 0) {
			long time = System.currentTimeMillis();
			try {
				synchronized (lock) {
					lock.wait(timeToWait);
					timeToWait -= System.currentTimeMillis() - time;
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
				logger.error(e);
				System.exit(1);
			}
		}
	}

	@Override
	public long getPeriod() {
		return period;
	}
}

@@ -191,16 +191,55 @@
  period;
+%0A%09private boolean periodChanged = true;
 %0A%0A%09priva
@@ -584,17 +584,28 @@
 iseconds
-%22
+ to %22 + this
 );%0A%09%09if 
@@ -762,16 +762,66 @@
 period;%0A
+%09%09synchronized (lock) %7B%0A%09%09%09periodChanged = true;%0A%09
 %09%09lock.n
@@ -832,16 +832,20 @@
 yAll();%0A
+%09%09%7D%0A
 %09%7D%0A%0A%09@Ov
@@ -907,16 +907,79 @@
 period;%0A
+%09%09logger.trace(%22begin waiting for %22 + timeToWait + %22 millis%22);%0A
 %09%09while 
@@ -1103,16 +1103,165 @@
 oWait);%0A
+%09%09%09%09%09if (periodChanged) %7B%0A%09%09%09%09%09%09logger.trace(%22period changed while waiting%22);%0A%09%09%09%09%09%09timeToWait = period;%0A%09%09%09%09%09%09periodChanged = false;%0A%09%09%09%09%09%7D else %7B%0A%09
 %09%09%09%09%09tim
@@ -1306,16 +1306,23 @@
 - time;%0A
+%09%09%09%09%09%7D%0A
 %09%09%09%09%7D%0A%09%09

Remove sleeping with timed out waiting