Java-Specific Syntax Sugar
This page only covers the convenient writing style unique to the Java SDK: wrap the existing
start()/stop()into try-with-resources. They are not a new feature; all the old APIs are kept.
PnSScope (try-with-resources)
PnSService Done AutoCloseable: Exit try the session close(). That's not the candy on this page.
PnSScope only takes care of start / stop:
- Enter the scope
start(); exit the scopestop(). - It doesn't replace it
close(); the conversation is still there. - There is no method
started(); check to see if it has been startedgetService().isStarted().
| Writing Style | Call |
|---|---|
| Standards API | device.start(); … device.stop(); |
| Syntax Sugar | try (PnSScope scope = PnSScope.of(device)) { ... } |
import com.darra.pns.service.PnSService;
import com.darra.pns.sugar.PnSScope;
try (PnSService device = new PnSService()) {
try (PnSScope scope = PnSScope.of(device)) {
// start() has been called
} // Inner layer: close() → stop()
} // Outer layer: close() closes the session
PnSScope.close() Idempotent; of() if a failure start() occurs, a half-open scope is not returned, and the business logic block is not entered. When leaving the scope, the result of the "walk close() " check is disabled stopChecked() , If you don't stop, it will fly off. PnSServiceException(Reason: getLastError()), it will not treat a failure as a graceful shutdown.
| Category | Members | Type | Reading and Writing | Note |
|---|---|---|---|---|
| Structure | PnSScope.of(service) | PnSScope | Static Methods | Immediately start(); failure does not return a half-open scope |
| Visit | getService() | PnSService | Read-only | Wrapped sessions do not transfer ownership |
| Start-Stop | close() | — | Methods | stopChecked(), not adjusted service.close(); throw a failure exception if deactivation fails PnSServiceException |
When to Use
- A section of stop-and-go traffic: Press "Start" to enter and "Stop" to exit; be sure not to skip any steps.
- Continuous operation: Don't use
PnSScope, do it yourselfstart()/stop(). - Close only the current session: Just
try (PnSService …)wear it on the outside—no need to layer itPnSScope.