Java Threading: Excessive CPU Utilization
<p>I'm using a service that reads messages from <code>Kafka</code> and pushes it into <code>Cassandra</code>.</p>

<p>I'm using a threaded architecture for the same.</p>

<p>There are say, <code>k threads</code> consuming from Kafka topic. These write into a queue, declared as:</p>

<pre><code>public static BlockingQueue&lt;&gt;
</code></pre>

<p>Now there are a number of threads, say <code>n</code>, which write into Cassandra. Here is the code that does that:</p>

<pre><code>public void run(){
    LOGGER.log(Level.INFO, "Thread Created: " +Thread.currentThread().getName());
    while (!Thread.currentThread().isInterrupted()) {
        Thread.yield();
        if (!content.isEmpty()) {
            try {
                JSONObject msg = content.remove();
                // JSON
                for(String tableName : tableList){
                    CassandraConnector.getSession().execute(createQuery(tableName, msg));
                }
            } catch (Exception e) {

            }
        }
    }
}
</code></pre>

<p><code>content</code> is the BlockingQueue used for read-write operations.</p>

<p>I'm extending the <code>Thread</code> class in the implementation of threading and there are a fixed number of threads that continue execution unless interrupted.</p>

<p>The problem is, this is using too much of CPU. Here is the first line of <code>top</code> command:</p>

<pre><code>  PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
46232 vishran+  20   0 3010804 188052  14280 S 137.8  3.3   5663:24 java
</code></pre>

<p>Here is the output of <code>strace</code> on a thread of this process:</p>

<pre><code>strace -t -p 46322
Process 46322 attached
15:18:47 sched_yield()                  = 0
15:18:47 sched_yield()                  = 0
15:18:47 sched_yield()                  = 0
15:18:47 sched_yield()                  = 0
15:18:47 sched_yield()                  = 0
15:18:47 sched_yield()                  = 0
15:18:47 sched_yield()                  = 0
15:18:47 sched_yield()                  = 0
15:18:47 sched_yield()                  = 0
15:18:47 sched_yield()                  = 0
15:18:47 sched_yield()                  = 0
15:18:47 sched_yield()                  = 0
15:18:47 sched_yield()                  = 0
15:18:47 sched_yield()                  = 0
15:18:47 sched_yield()                  = 0
....and so on
</code></pre>

<p>Why I am using <code>Thread.yield()</code>, is because of <a href="https://stackoverflow.com/questions/17070627/code-not-working-when-running-normally-but-working-in-debug-eclipse">this</a></p>

<p>If you want any other information for debugging, please let me know.</p>

<p>Now the question is, how can CPU utilization be minimized?</p>