java - Is there a danger in having a high number (20+) of simple threads? -
i writing game in java. have in-game tutorials. each tutorial 5-10 frame animation changes every second.
for each tutorial, have simple thread running:
int sleeptimemillis = 1000; public static void run() { while ( true ) { try { tutorialframe = ( tutorialframe + 1 ) % numberofframes; thread.sleep ( sleeptimemillis ); catch ( interruptedexception e ) {} } }
i have 10 of these running. time finish of them, imagine i'll have 50.
otherwise, game uses handful of threads: 1 windowing environment, 1 game logic, 1 rendering engine, , handful of other small ones here , there.
unsurprisingly, haven't noticed speed issues in game adding these threads. being said, i'm not knowledgeable on behind-the-scenes overhead having many threads within process.
i restructure program in different way if desirable reduce number of these tutorial threads.
so i'm asking whether it's worth time re-structure tutorials little share 1 thread, or whether makes sense leave things how are.
thanks!
threads tricky. first time people learn threads concept, think: "awesome, can run in parallel! use threads as possible everywhere!". there pitfalls. let's start cpu
, has multiple cores. first approximation, number of threads can run simultaneously equal number of cores (detailed comments on that, hyperthreading, welcome). so, if created 100 threads, 4 can executed simultaneously on machine 4 cores. , there thread scheduler, schedules threads execution.
the process when thread scheduler gives cpu
time 1 thread called context switch , takes time. moreover, when create new thread allocate memory stack. considering that, having many (let's 50) threads bad because:
- you using memory. on
x64
machine default thread stack size1mb
. 50 threads =50 mb
. context switch
happens frequently, loosing time on that.
you'll end having many threads, of time nothing, wasting resources. so, what's solution? instead of creating new threads each time need execute task asynchronously, can use executorservice
, there nice article on that. also, looking @ code, looks executing recurrent task. if so, can use timer class, create timertask , schedule @ fixed rate.
Comments
Post a Comment