No enclosing instance of type is accessible.

The whole code is:

public class ThreadLocalTest {
    ThreadLocal<Integer> globalint = new ThreadLocal<Integer>(){
        protected Integer initialValue() {
            return new Integer(0);

    public class MyThread implements Runnable{
        Integer myi;
        ThreadLocalTest mytest;

        public MyThread(Integer i, ThreadLocalTest test) {
            myi = i;
            mytest = test;

        public void run() {
            System.out.println("I am thread:" + myi);
            Integer myint = mytest.globalint.get();

    public static void main(String[] args){
        ThreadLocalTest test = new ThreadLocalTest();
        new Thread(new MyThread(new Integer(1), test)).start();

why the following snippet:

ThreadLocalTest test=new ThreadLocalTest();
    new Thread(new MyThread(new Integer(1),test)).start();

cause the following error:

No enclosing instance of type ThreadLocalTest is accessible. Must qualify the allocation with an enclosing instance of type ThreadLocalTest (e.g. A() where x is an instance of ThreadLocalTest).

The core problem is that: i want to initialize the inner class in the static methods. here are two solutions:

  1. make the inner class as outer class
  2. use outer reference like :

new Thread( MyRunnable(test)).start();//Use test object to create new

Leave a Comment