java - Stopping and starting Scheduled Executor properly -
i stopping , starting scheduled executor follows:
public class myactivity extends activity { scheduledexecutorservice executor; ... ... } protected void onresume() { super.onresume(); executor = executors.newsinglethreadscheduledexecutor(); executor.scheduleatfixedrate(periodictask, 0, 2, timeunit.seconds); system.out.println("activity has been resumed"); } protected void onstop() { super.onstop(); system.out.println("activity has been stopped"); executor.shutdownnow(); executor = null; } i wondering whether correct way stop , start executor service.
can implementation potentially cause problems down line?
i referred question in trying come solution this: android scheduledthreadpoolexecutor cause: null
i add critiques, approach solid.
first comment, there potential onstop() not called. such case described @ bottom of starting activity. such, consider moving executor creation , destruction different corresponding methods. if you'd keep creation in onresume(), place destruction , cleanup in onpause(). likewise, if you'd move creation oncreate(...) move destruction , cleanup ondestroy(). prefer latter 2 reasons: if it's tied activity , expect run in background put in oncreate(...) process can continue operating if activity no longer in focus. additionally, ondestroy() guaranteed called, if app forceable closed os.
as actual code cleanup, assume periodictask scheduledfuture, know assumptions. anyways, scheduledfuture has method canceling running task in addition being able shutdown service. can implement finish method along lines of:
private void finishscheduledexecutor() { if (periodictask != null) { periodictask.cancel(false); // true if can interrupted, false if you'd // finish current iteration } if (executor != null) { executor.shutdown(); // shutdown allow final iteration finish // executing shutdownnow() kill } } i explicitly close , release resources, threading involved, whenever possible. however, not absolutely necessary. shutdownnow() adequate terminating executorservice , periodictask.
Comments
Post a Comment