88import java .util .ArrayList ;
99import java .util .List ;
1010import java .util .concurrent .Executors ;
11+ import java .util .concurrent .ScheduledExecutorService ;
1112import java .util .concurrent .ScheduledFuture ;
1213import java .util .concurrent .TimeUnit ;
1314
@@ -27,33 +28,34 @@ public abstract class AbstractTickSpotifyAPI implements SpotifyAPI {
2728
2829 private SpotifyConfiguration configuration ;
2930
31+ private final ScheduledExecutorService executor = Executors .newSingleThreadScheduledExecutor ();
32+
3033 private ScheduledFuture <?> task ;
34+
3135 private long timeLastException = -1 ;
3236
3337 /**
3438 * Initialize the SpotifyAPI abstract tick implementation.
3539 * It will create a task that will update the current track and position every second.
3640 *
3741 * @return the initialized SpotifyAPI
38- * @throws IllegalStateException if the API is already initialized
42+ * @throws IllegalStateException if the API is already initialized or has been shutdown
3943 */
4044 @ Override
4145 public SpotifyAPI initialize (SpotifyConfiguration configuration ) {
4246 synchronized (this ) {
4347 this .configuration = configuration ;
4448
49+ if (this .executor .isShutdown ()) {
50+ throw new IllegalStateException ("This SpotifyAPI has been shutdown and cannot be reused" );
51+ }
52+
4553 if (this .isInitialized ()) {
46- throw new IllegalStateException ("The SpotifyAPI is already initialized" );
54+ throw new IllegalStateException ("This SpotifyAPI is already initialized" );
4755 }
4856
4957 // Start task to update every second
50- this .task = Executors .newScheduledThreadPool (1 )
51- .scheduleWithFixedDelay (
52- this ::onInternalTick ,
53- 0 ,
54- 1 ,
55- TimeUnit .SECONDS
56- );
58+ this .task = this .executor .scheduleWithFixedDelay (this ::onInternalTick , 0L , 1L , TimeUnit .SECONDS );
5759 }
5860 return this ;
5961 }
@@ -120,4 +122,10 @@ public void stop() {
120122 }
121123 }
122124 }
125+
126+ @ Override
127+ public void shutdown () {
128+ this .stop ();
129+ this .executor .shutdownNow ();
130+ }
123131}
0 commit comments