Skip to main content

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 scope stop().
  • It doesn't replace it close(); the conversation is still there.
  • There is no method started() ; check to see if it has been started getService().isStarted().
Writing StyleCall
Standards APIdevice.start(); … device.stop();
Syntax Sugartry (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.

CategoryMembersTypeReading and WritingNote
StructurePnSScope.of(service)PnSScopeStatic MethodsImmediately start(); failure does not return a half-open scope
VisitgetService()PnSServiceRead-onlyWrapped sessions do not transfer ownership
Start-Stopclose()—MethodsstopChecked(), 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 yourself start() / stop().
  • Close only the current session: Just try (PnSService …) wear it on the outside—no need to layer it PnSScope.