when I read FutureTask's run method, I found it use cas to set runner variable,

public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);
            }

Future can be used for executor to submit a task,the code like this:

Future<Integer> futureTask1 = executor.submit(callable)

in submit method, it will new FutureTask,RunnableFuture<T> ftask = newTaskFor(task), so run method in FutureTask doesn't have concurrency problem.
when use :

FutureTask futureTask = new FutureTask(new Callable() {
        @Override
        public int call() throws Exception {
            return 1;
        }
    })
new Thread(futureTask);
new Thread(futureTask);

diffrent thread use the same futureTask, so the run method have concurrency problem. But will this be used in reality?

Could someone tell me what I miss, thanks

?
If you just have 1 thread, using an executor or not, then there's no concurrency issue.
If you create two thread instances with the same FutureTask instance and start() them simultaneously then you are open to concurrency problems. I can't think of any reason why someone would do that in real life.

It's not clear exactly what your question is. Can you try asking it another way?

ps: there' a reason why the unsafe class is called unsafe. It's not safe.
I would want to see a code review by at least two experienced coders confirming that it is essential and the only way to meet the business spec before allowing its use

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.