3

For some academic research I need to simulate several threads running on a single processor.

I want to be able to insert *call_scheduler()* calls inside my code, in which the current "thread" will pause (remembering in which code line it is) and some scheduling function will decide which thread to let go.

In python, this could be implemented neatly using stackless python. Is there a java alternative?

I could implement it using real threads and some messaging queues (or pipes) that will force only one thread to run at a time - but this is an ugly and problematic solution.

1
  • I think there is no explicit way to do this in java, you have to just write some lines of code & you can use semaphores & priority queues Commented Jun 16, 2012 at 17:52

3 Answers 3

1

For cooperative user threads you could use Apache javaflow continuations: http://commons.apache.org/sandbox/javaflow/

I'd be interested in knowing how to implement a preemptive scheduler with this continuations package

Sign up to request clarification or add additional context in comments.

Comments

1

Scala actors framework like Akka do this. Each thread handles many actors that's how they created so efficiently. I recommend taking look at their source code.

Comments

0

Your question:

I could implement it using real threads and some messaging queues (or pipes) that will force only one thread to run at a time - but this is an ugly and problematic solution

Well if you want only a single thread to run at a time, by controlling the access of the thread on the object in a cleaner way, then use the Semaphores in java.util.concurrent package.

Semaphores sem = new Semaphores(1); // 1 here will mark that only one thread can have access

use sem.acquire() to get the key of the object, and when its done, use sem.release() then only another thread will get the access to this object.

7 Comments

But I want to be able to control from the scheduler-thread which thread will continue - so I'll need an array of semaphores, one for every thread.
create an HashMap of semaphores, so u can identify them by their keys, like first_thread, second_thread...etc
Is the native scheduler smart enough to understand that all the threads are waiting for the semaphore and only one thread can be active - so there is no reason to pause it?
Kumar Vivek Mitra - what's wrong with a unique index for every thread and an array?
using the new concurrent package, u can be assured of Thread Safety, thats it.... its just like if you want thread safety use StringBuffer class, else use StringBuilder..same difference here.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.