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:
the main thread works in isolation time, piling data collection;
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
.the reading thread polls
atomicreference
updates;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
Post a Comment