1

I have synchronized static methods in a class called Remote which are invoked from a service to fetch data from the network. The service is an IntentService that's started every time the user scrolls down a list in the UI and more items need to be fetched. The methods are synchronized because they're also called from another source, the syncadapter. Two calls to the same method in Remote can't interleave. But since my syncadapter is running on a separate process making the methods synchronized doesn't enforce thread safety and I was getting inconsistent states.

I solved this by switching the syncadapter back to run in the main process. More specifically removing the android:process value from the syncservice. But I was wondering if there was a much more robust way of doing, one which works irrespective of the syncadapter's location.

Michael Tedla
  • 1,079
  • 1
  • 12
  • 19
  • I haven't dealt with SyncAdapter much, but can you "force" a sync of the SyncAdapter instead of calling the synchronized method? – OneCricketeer Apr 20 '16 at 06:44
  • Yes but the logic is different. In the syncadapter i'm calling 3 or 4 of those synchronized methods, but when they're invoked via the service route only one of them is called at a time. – Michael Tedla Apr 20 '16 at 06:52

2 Answers2

1

A couple of points:

  • You can place all the network related code in one IntentService and send it intents from different places passing the task details as extras. IntentService will process these intents sequentially;

  • Within a process you can use FutureTask[1] or Volley's RequestFuture<>[2] class to synchronize your network requests.

[1] see an example of how to use FutureTask to prevent re-starting the same operation: http://jcip.net/listings/Memoizer3.java

[2] see examples here: Can I do a synchronous request with volley?

Community
  • 1
  • 1
dev.bmax
  • 8,998
  • 3
  • 30
  • 41
0

I am not a Android developer, but I think you may be getting confused between processes and threads.

A process has a self-contained execution environment. A process generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space. source

When you launch the SyncAdapter as a process it has no knowledge of the other process (or its threads) which are using the same syncronized block, and each will obtain a lock in their own memory space.

I think you should be launching the SyncAdapter as a thread from your main process, as this way the threads will block while the other is in the synchronized block.

rj93
  • 523
  • 8
  • 25