Skip to content

Commit ff6f7a6

Browse files
committed
Merge branch 'fix/98-defaultclock-volatile-timeunit' into develop
2 parents 0e76704 + 4212053 commit ff6f7a6

File tree

2 files changed

+22
-7
lines changed

2 files changed

+22
-7
lines changed

CHANGELOG.md

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,18 @@ This file lists modifications introduced by each version.
44

55
## [Unreleased]
66

7-
* Empty
7+
### DefaultClock class modifications
8+
9+
**Bug fixes in DefaultClock:**
10+
11+
* The `timeUnit` field of `DefaultClock` is now also `volatile` [[issue 98]][issue: #98]
12+
13+
Although not impacting with the `DefaultClock`'s usage, a potential multi-threading issue was present in its
14+
implementation. Since turning `timeUnit` into `volatile` did not prove to impact performances, the fix has been
15+
applied in order to set a good coding example.
16+
17+
18+
[issue: #98]: https://github.com/jbotsim/JBotSim/issues/98
819

920
## [1.2.0] - 2020/02/12
1021

lib/jbotsim-core/src/main/java/io/jbotsim/core/DefaultClock.java

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ public class DefaultClock extends Clock implements Runnable {
4343
final Lock lock = new ReentrantLock();
4444
final Condition shouldRunCondition = lock.newCondition();
4545

46-
private int delay = 0;
46+
volatile int timeUnit = 0;
4747

4848
public DefaultClock(ClockManager manager) {
4949
super(manager);
@@ -53,12 +53,12 @@ public DefaultClock(ClockManager manager) {
5353

5454
@Override
5555
public int getTimeUnit() {
56-
return delay;
56+
return timeUnit;
5757
}
5858

5959
@Override
60-
public void setTimeUnit(int delay) {
61-
this.delay = delay;
60+
public void setTimeUnit(int timeUnit) {
61+
this.timeUnit = timeUnit;
6262
}
6363

6464
@Override
@@ -105,8 +105,7 @@ public void run() {
105105
while (!running)
106106
shouldRunCondition.await();
107107

108-
if(delay != 0)
109-
Thread.sleep(delay);
108+
sleepIfNeeded(timeUnit);
110109

111110
if (running)
112111
manager.onClock();
@@ -119,4 +118,9 @@ public void run() {
119118
}
120119
}
121120
}
121+
122+
private void sleepIfNeeded(int delayMillis) throws InterruptedException {
123+
if(delayMillis != 0)
124+
Thread.sleep(delayMillis);
125+
}
122126
}

0 commit comments

Comments
 (0)