2

I have been learning and experimenting with multithreading in Java. I have a quad core processor (with Hyper-threading). If I have 1 thread go in an infinite loop in it's run() function, it utilizes my CPU for 90%.

How can I limit this to 1 core (ie. 25%) or it can't be done? I ask out of curiosity. Thank you in advance.


I was able to use upto 90%/core by using pure threads with a BlockingQueue instead of an executorService. I have yet to experiment with BlockingQueue on ExecutorService - but with a concurrent list the Executor service was being synchronized.

Thank you all for your help! I really appreciate it.

Struggler
  • 672
  • 2
  • 9
  • 22
  • 11
    It should in fact only use 25%. You may want to see what else you have running; maybe you forgot to close some instances. It would be awesome if it were so easy to get all the processing power out of a multicore system. – Zong Nov 11 '13 at 20:57
  • 3
    Note that certain tools report 100% CPU if one single core is fully utilized. – rolve Nov 11 '13 at 21:20
  • 3
    Look at the threads in debug window, there will be more than one doing things. One thread cannot and will not use more than 1 core at a time. – ajeh Nov 11 '13 at 21:21
  • If the reason you want to limit this is to limit the thread's resurce consumption, then you really ought to be using some other mechanism for this. For instance, see http://stackoverflow.com/questions/1202184/throttling-cpu-memory-usage-of-a-thread-in-java – AJMansfield Nov 11 '13 at 21:47
  • What do you do in that loop? Is that necessary at all? Maybe some short sleeps inside it would help you to utilize you cpu better. – Artur Nov 12 '13 at 09:21
  • @ZongZhengLi : Actually it should be half of it. Because of hyperthreading (www.tomshardware.com/forum/273660-28-task-manager-cores#). – Struggler Nov 14 '13 at 03:43

3 Answers3

2

A single thread can at best utilize 100% of one core. On a quad-core machine the Windows task manager reports this as 25% CPU usage, while Linux task manager reports this as 100% CPU usage.

So there is no need to assign this thread to one core, because it cannot use more than one core at any time by design.

TwoThe
  • 13,879
  • 6
  • 30
  • 54
1

It depends a bit on what your thread is doing.

Remember that other threads are running, for example the garbage collector and several JIT compiler threads. They will consume CPU too.

From my experience, it is not uncommon, to have 300% CPU (meaning your program uses 3 cores) in a single threaded program with heavy GC load just after starting it. This will level down after a while, when the JIT did most of its work.

Ingo
  • 36,037
  • 5
  • 53
  • 100
0

You can't do this in pure java, you need JNI to do this for you.

Just look at this, it may help you.

Trying
  • 14,004
  • 9
  • 70
  • 110