java - Can you push synchronization costs onto one thread? -


i have 2 threads: primary thread main processing of application, , secondary thread receives data batches primary thread , processes , outputs them, either user, file, or on network. in general, data should processed @ faster rate produced. ensure main thread never waits secondary thread. secondary thread can accept amount of overhead, expanding buffers, redoing work, , on, sole objective of maximizing performance of main thread. ideally main thread never synchronize @ all. there way push synchronization costs onto 1 thread in java?

this outline of solution:

  1. the main thread works in isolation time, piling data collection;

  2. when has generated nice batch, it:

    i. creates new collection itself;

    ii. sets filled-up collection aside, available picked reading thread;

    iii. cases collection atomicreference.

  3. the reading thread polls atomicreference updates;

  4. when notices has been set, picks batch, casing null shared reference, main thread knows can put collection in.

this has negligible coordination costs main thread (just 1 cas operation per batch) assuming reference null when it's time share new batch.

the reading thread may run busy loop polling shared reference, sleeping small amount of time each time reads null. best technique make thread sleep short time is

locksupport.parknanos(1); 

which typically sleep 30 µs , whole loop consume 2-3% cpu time. use longer pause, of course, if want bring down cpu time more.

note coordination techniques make thread wait in wait set impose large latency on both sides, should stay away them if, say, 1 ms latency big concern you.


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -