Java Doc for FJTaskRunner.java in  » Database-JDBC-Connection-Pool » proxool » org » logicalcobwebs » concurrent » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Database JDBC Connection Pool » proxool » org.logicalcobwebs.concurrent 
Source Cross Reference  Class Diagram Java Document (Java Doc) 


java.lang.Object
   java.lang.Thread
      org.logicalcobwebs.concurrent.FJTaskRunner

FJTaskRunner
public class FJTaskRunner extends Thread (Code)
Specialized Thread subclass for running FJTasks.

Each FJTaskRunner keeps FJTasks in a double-ended queue (DEQ). Double-ended queues support stack-based operations push and pop, as well as queue-based operations put and take. Normally, threads run their own tasks. But they may also steal tasks from each others DEQs.

The algorithms are minor variants of those used in Cilk and Hood, and to a lesser extent Filaments, but are adapted to work in Java.

The two most important capabilities are:

  • Fork a FJTask:
     Push task onto DEQ
     
  • Get a task to run (for example within taskYield)
     If DEQ is not empty,
     Pop a task and run it.
     Else if any other DEQ is not empty,
     Take ("steal") a task from it and run it.
     Else if the entry queue for our group is not empty,
     Take a task from it and run it.
     Else if current thread is otherwise idling
     If all threads are idling
     Wait for a task to be put on group entry queue
     Else
     Yield or Sleep for a while, and then retry
     
The push, pop, and put are designed to only ever called by the current thread, and take (steal) is only ever called by other threads. All other operations are composites and variants of these, plus a few miscellaneous bookkeeping methods.

Implementations of the underlying representations and operations are geared for use on JVMs operating on multiple CPUs (although they should of course work fine on single CPUs as well).

A possible snapshot of a FJTaskRunner's DEQ is:

 0     1     2     3     4     5     6    ...
 +-----+-----+-----+-----+-----+-----+-----+--
 |     |  t  |  t  |  t  |  t  |     |     | ...  deq array
 +-----+-----+-----+-----+-----+-----+-----+--
 ^                       ^
 base                    top
 (incremented                     (incremented
 on take,                         on push
 decremented                     decremented
 on put)                          on pop)
 

FJTasks are held in elements of the DEQ. They are maintained in a bounded array that works similarly to a circular bounded buffer. To ensure visibility of stolen FJTasks across threads, the array elements must be volatile. Using volatile rather than synchronizing suffices here since each task accessed by a thread is either one that it created or one that has never seen before. Thus we cannot encounter any staleness problems executing run methods, although FJTask programmers must be still sure to either synch or use volatile for shared data within their run methods.

However, since there is no way to declare an array of volatiles in Java, the DEQ elements actually hold VolatileTaskRef objects, each of which in turn holds a volatile reference to a FJTask. Even with the double-indirection overhead of volatile refs, using an array for the DEQ works out better than linking them since fewer shared memory locations need to be touched or modified by the threads while using the DEQ. Further, the double indirection may alleviate cache-line sharing effects (which cannot otherwise be directly dealt with in Java).

The indices for the base and top of the DEQ are declared as volatile. The main contention point with multiple FJTaskRunner threads occurs when one thread is trying to pop its own stack while another is trying to steal from it. This is handled via a specialization of Dekker's algorithm, in which the popping thread pre-decrements top, and then checks it against base. To be conservative in the face of JVMs that only partially honor the specification for volatile, the pop proceeds without synchronization only if there are apparently enough items for both a simultaneous pop and take to succeed. It otherwise enters a synchronized lock to check if the DEQ is actually empty, if so failing. The stealing thread does almost the opposite, but is set up to be less likely to win in cases of contention: Steals always run under synchronized locks in order to avoid conflicts with other ongoing steals. They pre-increment base, and then check against top. They back out (resetting the base index and failing to steal) if the DEQ is empty or is about to become empty by an ongoing pop.

A push operation can normally run concurrently with a steal. A push enters a synch lock only if the DEQ appears full so must either be resized or have indices adjusted due to wrap-around of the bounded DEQ. The put operation always requires synchronization.

When a FJTaskRunner thread has no tasks of its own to run, it tries to be a good citizen. Threads run at lower priority while scanning for work.

If the task is currently waiting via yield, the thread alternates scans (starting at a randomly chosen victim) with Thread.yields. This is well-behaved so long as the JVM handles Thread.yield in a sensible fashion. (It need not. Thread.yield is so underspecified that it is legal for a JVM to treat it as a no-op.) This also keeps things well-behaved even if we are running on a uniprocessor JVM using a simple cooperative threading model.

If a thread needing work is is otherwise idle (which occurs only in the main runloop), and there are no available tasks to steal or poll, it instead enters into a sleep-based (actually timed wait(msec)) phase in which it progressively sleeps for longer durations (up to a maximum of FJTaskRunnerGroup.MAX_SLEEP_TIME, currently 100ms) between scans. If all threads in the group are idling, they further progress to a hard wait phase, suspending until a new task is entered into the FJTaskRunnerGroup entry queue. A sleeping FJTaskRunner thread may be awakened by a new task being put into the group entry queue or by another FJTaskRunner becoming active, but not merely by some DEQ becoming non-empty. Thus the MAX_SLEEP_TIME provides a bound for sleep durations in cases where all but one worker thread start sleeping even though there will eventually be work produced by a thread that is taking a long time to place tasks in DEQ. These sleep mechanics are handled in the FJTaskRunnerGroup class.

Composite operations such as taskJoin include heavy manual inlining of the most time-critical operations (mainly FJTask.invoke). This opens up a few opportunities for further hand-optimizations. Until Java compilers get a lot smarter, these tweaks improve performance significantly enough for task-intensive programs to be worth the poorer maintainability and code duplication.

Because they are so fragile and performance-sensitive, nearly all methods are declared as final. However, nearly all fields and methods are also declared as protected, so it is possible, with much care, to extend functionality in subclasses. (Normally you would also need to subclass FJTaskRunnerGroup.)

None of the normal java.lang.Thread class methods should ever be called on FJTaskRunners. For this reason, it might have been nicer to declare FJTaskRunner as a Runnable to run within a Thread. However, this would have complicated many minor logistics. And since no FJTaskRunner methods should normally be called from outside the FJTask and FJTaskRunnerGroup classes either, this decision doesn't impact usage.

You might think that layering this kind of framework on top of Java threads, which are already several levels removed from raw CPU scheduling on most systems, would lead to very poor performance. But on the platforms tested, the performance is quite good.

[ Introduction to this package. ]
See Also:   FJTask
See Also:   FJTaskRunnerGroup


Inner Class :final protected static class VolatileTaskRef

Field Summary
final static  booleanCOLLECT_STATS
     Compile-time constant for statistics gathering.
final protected static  intINITIAL_CAPACITY
     FJTasks are held in an array-based DEQ with INITIAL_CAPACITY elements.
final protected static  intMAX_CAPACITY
     The maximum supported DEQ capacity.
protected  booleanactive
     Record whether current thread may be processing a task (i.e., has been started and is not in an idle wait).
final protected  Objectbarrier
     An extra object to synchronize on in order to achieve a memory barrier.
protected volatile  intbase
     Current base of DEQ.
protected  VolatileTaskRef[]deq
     The DEQ array.
final protected  FJTaskRunnerGroupgroup
    
protected  intrunPriority
    
protected  intruns
    
protected  intscanPriority
    
protected  intscans
    
protected  intsteals
    
protected volatile  inttop
     Current top of DEQ.
final protected  RandomvictimRNG
    

Constructor Summary
protected  FJTaskRunner(FJTaskRunnerGroup g)
    

Method Summary
protected  voidcheckOverflow()
     Adjust top and base, and grow DEQ if necessary. Called only while DEQ synch lock being held. We don't expect this to be called very often.
final protected  voidcoInvoke(FJTask w, FJTask v)
    
final protected  voidcoInvoke(FJTask[] tasks)
    
final protected synchronized  FJTaskconfirmPop(int provisionalTop)
     Check under synch lock if DEQ is really empty when doing pop.
protected  FJTaskconfirmTake(int oldBase)
    
protected  intdeqSize()
    
final protected  FJTaskRunnerGroupgetGroup()
    
final protected  FJTaskpop()
     Return a popped task, or null if DEQ is empty. Called ONLY by current thread.

This is not usually called directly but is instead inlined in callers.

final protected  voidpush(FJTask r)
     Push a task onto DEQ.
final protected synchronized  voidput(FJTask r)
     Enqueue task at base of DEQ. Called ONLY by current thread. This method is currently not called from class FJTask.
public  voidrun()
    
protected  voidscan(FJTask waitingFor)
     Do all but the pop() part of yield or join, by traversing all DEQs in our group looking for a task to steal.
protected  voidscanWhileIdling()
     Same as scan, but called when current thread is idling.
protected  voidsetRunPriority(int pri)
     Set the priority to use while running tasks.
protected  voidsetScanPriority(int pri)
     Set the priority to use while scanning.
protected  voidslowCoInvoke(FJTask w, FJTask v)
    
protected  voidslowCoInvoke(FJTask[] tasks)
    
protected synchronized  voidslowPush(FJTask r)
    
final protected synchronized  FJTasktake()
     Take a task from the base of the DEQ.
final protected  voidtaskJoin(FJTask w)
     Process tasks until w is done.
final protected  voidtaskYield()
     Execute a task in this thread.

Field Detail
COLLECT_STATS
final static boolean COLLECT_STATS(Code)
Compile-time constant for statistics gathering. Even when set, reported values may not be accurate since all are read and written without synchronization.



INITIAL_CAPACITY
final protected static int INITIAL_CAPACITY(Code)
FJTasks are held in an array-based DEQ with INITIAL_CAPACITY elements. The DEQ is grown if necessary, but default value is normally much more than sufficient unless there are user programming errors or questionable operations generating large numbers of Tasks without running them. Capacities must be a power of two.



MAX_CAPACITY
final protected static int MAX_CAPACITY(Code)
The maximum supported DEQ capacity. When exceeded, FJTaskRunner operations throw Errors



active
protected boolean active(Code)
Record whether current thread may be processing a task (i.e., has been started and is not in an idle wait). Accessed, under synch, ONLY by FJTaskRunnerGroup, but the field is stored here for simplicity.



barrier
final protected Object barrier(Code)
An extra object to synchronize on in order to achieve a memory barrier.



base
protected volatile int base(Code)
Current base of DEQ. Acts like a take-pointer in an array-based bounded queue. Same bounds and usage as top.



deq
protected VolatileTaskRef[] deq(Code)
The DEQ array.



group
final protected FJTaskRunnerGroup group(Code)
The group of which this FJTaskRunner is a member *



runPriority
protected int runPriority(Code)
Priority to use while running tasks *



runs
protected int runs(Code)
Total number of tasks run *



scanPriority
protected int scanPriority(Code)
Priority to use while scanning for work *



scans
protected int scans(Code)
Total number of queues scanned for work *



steals
protected int steals(Code)
Total number of tasks obtained via scan *



top
protected volatile int top(Code)
Current top of DEQ. Generally acts just like a stack pointer in an array-based stack, except that it circularly wraps around the array, as in an array-based queue. The value is NOT always kept within 0 ... deq.length though. The current top element is always at top & (deq.length-1). To avoid integer overflow, top is reset down within bounds whenever it is noticed to be out out bounds; at worst when it is at 2 * deq.length.



victimRNG
final protected Random victimRNG(Code)
Random starting point generator for scan() *




Constructor Detail
FJTaskRunner
protected FJTaskRunner(FJTaskRunnerGroup g)(Code)
Constructor called only during FJTaskRunnerGroup initialization




Method Detail
checkOverflow
protected void checkOverflow()(Code)
Adjust top and base, and grow DEQ if necessary. Called only while DEQ synch lock being held. We don't expect this to be called very often. In most programs using FJTasks, it is never called.



coInvoke
final protected void coInvoke(FJTask w, FJTask v)(Code)
A specialized expansion of w.fork(); invoke(v); w.join();



coInvoke
final protected void coInvoke(FJTask[] tasks)(Code)
Array-based version of coInvoke



confirmPop
final protected synchronized FJTask confirmPop(int provisionalTop)(Code)
Check under synch lock if DEQ is really empty when doing pop. Return task if not empty, else null.



confirmTake
protected FJTask confirmTake(int oldBase)(Code)
double-check a potential take



deqSize
protected int deqSize()(Code)
Current size of the task DEQ *



getGroup
final protected FJTaskRunnerGroup getGroup()(Code)
Return the FJTaskRunnerGroup of which this thread is a member



pop
final protected FJTask pop()(Code)
Return a popped task, or null if DEQ is empty. Called ONLY by current thread.

This is not usually called directly but is instead inlined in callers. This version differs from the cilk algorithm in that pop does not fully back down and retry in the case of potential conflict with take. It simply rechecks under synch lock. This gives a preference for threads to run their own tasks, which seems to reduce flailing a bit when there are few tasks to run.




push
final protected void push(FJTask r)(Code)
Push a task onto DEQ. Called ONLY by current thread.



put
final protected synchronized void put(FJTask r)(Code)
Enqueue task at base of DEQ. Called ONLY by current thread. This method is currently not called from class FJTask. It could be used as a faster way to do FJTask.start, but most users would find the semantics too confusing and unpredictable.



run
public void run()(Code)
Main runloop



scan
protected void scan(FJTask waitingFor)(Code)
Do all but the pop() part of yield or join, by traversing all DEQs in our group looking for a task to steal. If none, it checks the entry queue.

Since there are no good, portable alternatives, we rely here on a mixture of Thread.yield and priorities to reduce wasted spinning, even though these are not well defined. We are hoping here that the JVM does something sensible.
Parameters:
  waitingFor - if non-null, the current task being joined




scanWhileIdling
protected void scanWhileIdling()(Code)
Same as scan, but called when current thread is idling. It repeatedly scans other threads for tasks, sleeping while none are available.

This differs from scan mainly in that since there is no reason to return to recheck any condition, we iterate until a task is found, backing off via sleeps if necessary.




setRunPriority
protected void setRunPriority(int pri)(Code)
Set the priority to use while running tasks. Same usage and rationale as setScanPriority.



setScanPriority
protected void setScanPriority(int pri)(Code)
Set the priority to use while scanning. We do not bother synchronizing access, since by the time the value is needed, both this FJTaskRunner and its FJTaskRunnerGroup will necessarily have performed enough synchronization to avoid staleness problems of any consequence.



slowCoInvoke
protected void slowCoInvoke(FJTask w, FJTask v)(Code)
Backup to handle noninlinable cases of coInvoke



slowCoInvoke
protected void slowCoInvoke(FJTask[] tasks)(Code)
Backup to handle atypical or noninlinable cases of coInvoke



slowPush
protected synchronized void slowPush(FJTask r)(Code)
Handle slow case for push



take
final protected synchronized FJTask take()(Code)
Take a task from the base of the DEQ. Always called by other threads via scan()



taskJoin
final protected void taskJoin(FJTask w)(Code)
Process tasks until w is done. Equivalent to while(!w.isDone()) taskYield();



taskYield
final protected void taskYield()(Code)
Execute a task in this thread. Generally called when current task cannot otherwise continue.



Fields inherited from java.lang.Thread
final public static int MAX_PRIORITY(Code)(Java Doc)
final public static int MIN_PRIORITY(Code)(Java Doc)
final public static int NORM_PRIORITY(Code)(Java Doc)

Methods inherited from java.lang.Thread
public static int activeCount()(Code)(Java Doc)
final public void checkAccess()(Code)(Java Doc)
native public int countStackFrames()(Code)(Java Doc)
native public static Thread currentThread()(Code)(Java Doc)
public void destroy()(Code)(Java Doc)
public static void dumpStack()(Code)(Java Doc)
public static int enumerate(Thread tarray)(Code)(Java Doc)
public static Map<Thread, StackTraceElement[]> getAllStackTraces()(Code)(Java Doc)
public ClassLoader getContextClassLoader()(Code)(Java Doc)
public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()(Code)(Java Doc)
public long getId()(Code)(Java Doc)
final public String getName()(Code)(Java Doc)
final public int getPriority()(Code)(Java Doc)
public StackTraceElement[] getStackTrace()(Code)(Java Doc)
public State getState()(Code)(Java Doc)
final public ThreadGroup getThreadGroup()(Code)(Java Doc)
public UncaughtExceptionHandler getUncaughtExceptionHandler()(Code)(Java Doc)
native public static boolean holdsLock(Object obj)(Code)(Java Doc)
public void interrupt()(Code)(Java Doc)
public static boolean interrupted()(Code)(Java Doc)
final native public boolean isAlive()(Code)(Java Doc)
final public boolean isDaemon()(Code)(Java Doc)
public boolean isInterrupted()(Code)(Java Doc)
final public synchronized void join(long millis) throws InterruptedException(Code)(Java Doc)
final public synchronized void join(long millis, int nanos) throws InterruptedException(Code)(Java Doc)
final public void join() throws InterruptedException(Code)(Java Doc)
final public void resume()(Code)(Java Doc)
public void run()(Code)(Java Doc)
public void setContextClassLoader(ClassLoader cl)(Code)(Java Doc)
final public void setDaemon(boolean on)(Code)(Java Doc)
public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh)(Code)(Java Doc)
final public void setName(String name)(Code)(Java Doc)
final public void setPriority(int newPriority)(Code)(Java Doc)
public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh)(Code)(Java Doc)
native public static void sleep(long millis) throws InterruptedException(Code)(Java Doc)
public static void sleep(long millis, int nanos) throws InterruptedException(Code)(Java Doc)
public synchronized void start()(Code)(Java Doc)
final public void stop()(Code)(Java Doc)
final public synchronized void stop(Throwable obj)(Code)(Java Doc)
final public void suspend()(Code)(Java Doc)
public String toString()(Code)(Java Doc)
native public static void yield()(Code)(Java Doc)

Methods inherited from java.lang.Object
native protected Object clone() throws CloneNotSupportedException(Code)(Java Doc)
public boolean equals(Object obj)(Code)(Java Doc)
protected void finalize() throws Throwable(Code)(Java Doc)
final native public Class getClass()(Code)(Java Doc)
native public int hashCode()(Code)(Java Doc)
final native public void notify()(Code)(Java Doc)
final native public void notifyAll()(Code)(Java Doc)
public String toString()(Code)(Java Doc)
final native public void wait(long timeout) throws InterruptedException(Code)(Java Doc)
final public void wait(long timeout, int nanos) throws InterruptedException(Code)(Java Doc)
final public void wait() throws InterruptedException(Code)(Java Doc)

www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.