首页 > 在类中定义静态成员变量,对象初始化后,该变量指向this,作用是什么?

在类中定义静态成员变量,对象初始化后,该变量指向this,作用是什么?

package com.umeox.babywei.k3.service;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

@Component
public class JdbcExecutor implements InitializingBean, DisposableBean {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    public static JdbcExecutor instance;

    private ThreadPoolTaskExecutor jdbcExecutor = null;

    private volatile boolean stopping = false;

    @Override
    public void afterPropertiesSet() throws Exception {
        instance = this;

        int limit = 100;

        // 实际扫描线程池
        jdbcExecutor = new ThreadPoolTaskExecutor();
        jdbcExecutor.setCorePoolSize(limit / 5);
        jdbcExecutor.setMaxPoolSize(limit);
        jdbcExecutor.setWaitForTasksToCompleteOnShutdown(true);
        jdbcExecutor.afterPropertiesSet();

        // Thread thread = new Thread(new Runnable() {
        // @Override
        // public void run() {
        // while (!stopping) {
        //
        // logger.info("JdbcExecutor Status\n. {}",
        // jdbcExecutor.getThreadPoolExecutor());
        //
        // try {
        // Thread.sleep(60 * 1000);
        // } catch (InterruptedException e) {
        // e.printStackTrace();
        // }
        // }
        // }
        // });
        //
        // thread.start();
    }

    public void submit(Runnable runnable) {
        this.jdbcExecutor.submit(runnable);
    }

    @Override
    public void destroy() throws Exception {
        stopping = true;
    }

    public Future<?> submit(Callable<?> callable) {
        return this.jdbcExecutor.submit(callable);
    }
}

感觉没有多大意义呢,不像是单例模式


猜测这个作者的意图是希望在当前类的一个实例属性被设置后afterPropertiesSet)激活一个当前类的静态实例指向该实例。
他允许创建多个实例,但静态的instance永远指向最后一个调用afterPropertiesSet的那一个。
不知道他为什么这么写,也许是业务需要,但可能单例模式更好一点。


根据public static JdbcExecutor instance;的定义为public的判断,可能只是为了其他地方不方便取到spring的bean而设计的,这样就可以直接用静态变量来获取当前的实例了。

【热门文章】
【热门文章】