TornadoVM icon indicating copy to clipboard operation
TornadoVM copied to clipboard

TornadoCoreRuntime.executorThreadFactory is not thread safe

Open vsilaev opened this issue 3 years ago • 0 comments

In current code:

    private static final ThreadFactory executorThreadFactory = new ThreadFactory() {
        private int threadId = 0; // <-- a field with non-synchronized access

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r, String.format("TornadoExecutorThread - %d", threadId));
            thread.setDaemon(true);
            threadId++;
            return thread;
        }
    };

Field threadId is used from concurrent threads (due to the nature of ThreadFactory and ExecutorService-s that using it). Hence access to this field should be either synchronized or replaced with better atomic type:

    private static final ThreadFactory executorThreadFactory = new ThreadFactory() {
        private final AtomicLong threadId = new AtomicLong(0); // <-- a field with non-synchronized access

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r, String.format("TornadoExecutorThread - %d", threadId.incrementAndGet()));
            thread.setDaemon(true);
            return thread;
        }
    };

vsilaev avatar Dec 24 '21 14:12 vsilaev