First best practice is to use ServiceTracker instead of using the service API directly.
1) st is a normal java object reference and st can't become null after the null check. 2) Null test is usefull. The service could be implemented by a ServiceFactory which could be erroneous and thus getService could return null. 3) No BJ Hargrave Senior Technical Staff Member, IBM OSGi Fellow and CTO of the OSGi Alliance [EMAIL PROTECTED] Office: +1 386 848 1781 Mobile: +1 386 848 3788 ----- Original Message ----- From: "Steven E. Harris" [EMAIL PROTECTED] Sent: 05/08/2007 09:58 AM To: [email protected] Subject: [osgi-dev] Expecting NullPointerExceptions from ServiceReferences -- style tips Consider the following code: // BundleContext bc ... final ServiceReference[] refs = bc.getServiceReferences( SomeType.class.getName(), "(foo=bar)" ); if ( null != refs ) for ( ServiceReference ref: refs ) { final SomeType st = (SomeType) bc.getService( ref ); try { if ( null != st ) return st.use( 42 ); } catch (NullPointerException ignored) { // Ignore it, as the service went away. } finally { bc.ungetService( ref ); } } Here we grab all known ServiceReferences for a given object class and filter, walk the set, and attempt to call on the first valid reference. We attempt to catch a NPE that might arise from the "st.use( 42 )" call if the object referenced by "st" were to disappear immediately after the null check but before we could call call its use() method. Several questions: o Could this NPE actually arise here, or is "st" pinned in memory by the reference we're holding to it? o Is the preceding null test then spurious? o Should I bother with BundleContext.ungetService() if BundleContext.getService() had returned null? -- Steven E. Harris _______________________________________________ OSGi Developer Mail List [email protected] http://www2.osgi.org/mailman/listinfo/osgi-dev _______________________________________________ OSGi Developer Mail List [email protected] http://www2.osgi.org/mailman/listinfo/osgi-dev
