2

I need to access an API using their SDK.

Access (well, anything I need to access) requires the use of a context object. The same one.

Context context;

It is running with the possiblity (well, certainty) that multiple threads will access this same context object to perform various operations (via the 'context' object)

So, is all that is needed for Thread-Safety is to refer to it only via a synchronized getter()?

Example:

getContext().someOperation()
getContext().anotherOperation()

Definition:

public synchronized Context getContext() { return context; }
Community
  • 1
  • 1
ycomp
  • 8,316
  • 19
  • 57
  • 95
  • Is the `Context` class thread safe? – assylias Oct 19 '15 at 15:18
  • No, a synchronized getter wouldn't be enough if the object itself is not threadsafe, because the usage of the Object would take more time than just `getting` the object. So there will be concurrent access on the same instance possible. – dognose Oct 19 '15 at 15:20
  • not entirely sure, but I can't see that it wouldn't be - I don't know how their API would function if it wasn't. Plus some of the documentation mentions that certain things (that definitely access the context) run in different threads. So I would be fairly certain it is. – ycomp Oct 19 '15 at 15:21

2 Answers2

2

No, synchronizing only on the getter is not an option. There are two possibilities:

  • the Context object is threadsafe, in which case you don't need to synchronize on anything at all.

  • the Context object isn't threadsafe, in which case both your getter and anything else that touches it all have to synchronize on the same lock.

You should read up on the API and see whether the object is in fact threadsafe, usually with APIs that require sharing something like this it's only good sense from the API provider's point of view to protect it from concurrent changes.

Assuming the documentation is inadequate, which is typical, reasoning about the spec from the implementer's point of view can be useful. In this case, if the API requires synchronization, what would be the lock that you would synchronize on? For synchronization to work you need a shared lock. Usually the container is a lot better positioned to handle this kind of concern than you are on the client-side.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
  • @ycomp: not hard to believe. the java apis are not clear all the time either. see http://stackoverflow.com/a/31588609/217324 – Nathan Hughes Oct 19 '15 at 15:24
1

The synchronized keyword is pointing to the scope of the method. So only that method is thread-safe.

I.e., only that method can be called by one thread at a time (per instance, of course since the method is an instance method).

To make the context thread-safe, any actions on it need to occur within a synchronized block or method (unless the actions of the Context object are already thread-safe, of course).

ryuu9187
  • 1,162
  • 7
  • 15