Thread safety of mutable fields in Tasks (when multithreaded scheduler is used)

10 views
Skip to first unread message

Igor Lukyanov

unread,
Jun 22, 2020, 6:00:15 PM6/22/20
to kilimthreads
Hello.
Thank you for developing such a great framework. Could you please help me with the following?
If the task is executed on different threads (ForkJonScheduler for instance), should any synchronization measures be taken to ensure that modifications of mutable fields flushed to RAM from CPU cache or not? Like using volatile keywords, access within a critical section, etc. 

public class Actor extends Task {
    private int a = 0;
    private volatile int b = 0;
    ...
}

public class Actor extends Task {
    private HashMap a = 0;
    private HashMap b = 0;
    ...
    public void access(){
        synchronized(?){
        a.put(new Object(), new Object());
        }
    }
}

Thank you.

sriram srinivasan

unread,
Jun 22, 2020, 11:41:32 PM6/22/20
to kilimt...@googlegroups.com
No, you do not have to declare any private state volatile, since the very act of scheduling involves synchronization, and that would 'effectively flush’ (1) to RAM. You can call ordinary synchronized methods as you have shown.

However, you CANNOT call pausable methods within a synchronized block. The weaver will recognize it and not allow it. The reason is as follows:
'synchronized' gets translated to a pair of monitorenter and monitorexit VM calls. At monitorenter, the VM associates the monitor’s lock with the thread from which it is being called. Clearly, it makes no sense for the rest of the code including monitorexit to run in a different thread. The VM detects this at run-time and throws a runtime exception. We detect this at compile time and disallow it.

If you must use locks, you can use kilim’s locks that are aware of this behavior.

Hope this helps.

—sriram.
Reply all
Reply to author
Forward
0 new messages