# Monday, 09 July 2012

Heroku supports running non-web Java processes called "workers". Heroku Workers are an economical solution for executing long running processes, such as waiting for events in a messaging queue.

A worker is basically a Java class that sits in a while loop.

public class WorkerProcess 
{
	public static void main(String[] args)
	{
		while(true) {
			try { 
				Thread.sleep(1000);
			} catch(InterruptedException e) {}            
			System.out.println("Worker process woke up");        
		}
	}    
}

The worker process utilizes its dyno (virtual machine) 100%, therefore is billed at the full rate.

For processes that make asynchronous calls and wait for a response, a single threaded worker can be wasteful. The examples below demonstrate how to spawn several threads within a Heroku Java worker.

public class WorkerProcess
{
	public static void main(String[] args)
	{
		final int MAX_THREADS = 100;
		
		for(int i = 0; i < MAX_THREADS; i++){
			WorkerThread t = new WorkerThread (i);
			new Thread(t).start();
		}
	}
}
public class WorkerThread implements Runnable 
{
	final private int thread_id;

	WorkerThread(int n) 
    {    	
		this.thread_id = n; 
    }
    
    public void run() 
    {
    	while(true){
    		try{
    			System.out.println("Thread " + this.thread_id);
    			//Do something here
    		}
    		catch(Exception e){
    			
    		}
    	}
    }
}
This example of 100 threads runs fine on the Heroku cedar stack. At the time of this writing, Heroku worker threads were bound by memory and not a fixed number of threads.

Resources:
Run non-web Java processes on Heroku
Git repository of Heroku demo (replace the demo classes with the code above in this article)
Comments are closed.