Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to make sure that calling an external method is thread safe?

For the following code:

method() { object.externalMethod(); }

If externalMethod() is not thread safe. Say, it starts multiple threads, which do some unsafe stuffs. Can we still make sure method() is thread safe, with no knowledge of externalMethod's implementation? I believe adding "synchronized" is not enough here.

like image 998
user3237582 Avatar asked Oct 02 '22 18:10

user3237582


1 Answers

Adding synchronized is enough - so long as you synchronize onto all access to the object, not just onto all access to externalMethod.

Unless of course the internals of the object are failing to synchronize properly, in which case you are indeed unable to do anything. The object should document the correct way to interact with it though.

like image 164
Tim B Avatar answered Oct 05 '22 10:10

Tim B