Java static关键词

前言

使用static关键词描述变量在内存中只有一份,是是一个共享全局变量。对于对象来说是单例的。

在之前的文章中描述过enum在使用过程中遇到的问题:

http://blog.csdn.net/xiaoxiaoxuanao/article/details/52573863

因为枚举实际上是单例的,如果试图去修改枚举里对象的属性值,可能会引发访问问题。

就我目前的开发经验来看,对象单例一般有两种方式创建

不能使用static对象的情况

平时在做web开发的过程中经常会看到有程序员写出类似于下面的代码:

@Controller
@RequestMapping("example")
public class ExampleController {
    private static Integer index = 0;

    @RequestMapping("test")
    public void addIndex(){
        index++;
    }
}

这段代码在单个client访问的时候不会有任何问题,因为每访问一次index就会加1,但是多个client访问的时候,不同的client的访问会导致index的值彼此影响;另外一个是多个客户端并发访问的时候index的值会出现不确定的情况。

总结1:不要试图改变共享的全局变量的属性值或者值,如果有类似的需求,最好封装在单个线程内部去做。

务必使用static的情况

static的对象在内存中只有一份,所以那些资源性的东西,比方说HttpClient,redisResource,curatorclient非常适合建立static的对象,这样保证对象在内存中只有一份。这种在内存中只有一份的对象有很多好处:

  • 可以大大节省请求的访问时间,因为避免了每次使用资源的时候都去建立连接或者创建对象
  • 相比于在方法内创建对象,单例对象不会随着方法的退出被jvm回收掉,因而那种需要永久保留的对象都要创建成static的
  • 资源只有一份的时候方便jvm对象的回收,此时jvm只需要回收一次,而那种每次需要资源时都创建对象的方式往往需要使用完后手动执行关闭比方说下面的代码:
 public String setExpire(String cacheKey, int validTimeInSeconds, String value){
    Jedis redis = getResource();
    String resultData = null;
    try {
      resultData = redis.setex(cacheKey, validTimeInSeconds, value);
      this.lastVisitCache.set(cacheKey, value);
    } catch (Exception e) {
      LOGGER.error("{}", e.getMessage(), e);
    } finally {
      returnResource(redis);
    }
    return resultData;
  }

例子:
(1)创建curatorframework对象:

public abstract class PathCacheExample {
    private static final String PATH = "/example";
    static CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", new ExponentialBackoffRetry(1000, 3));
    static PathChildrenCache cache = new PathChildrenCache(client, PATH, true);
    static TreeCache treeCache = new TreeCache(client, PATH);

    public static void main(String[] args) {
        start();
    }

    public static void start() {
        try {
            client.start();
            cache.start();
            treeCache.start();

            addPathChildListener(cache);
            //addTreeListener(treeCache);
            //processCommands(client, cache);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void shutdown() {
        CloseableUtils.closeQuietly(cache);
        CloseableUtils.closeQuietly(client);
    }
    }

(2)httpclient对象的创建:

public class HttpClientBasedQdContactFetcher implements QdContactFetcher {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientBasedQdContactFetcher.class);
    private static final CloseableHttpClient closeableHttpClient = buildClient();
    private CloseableHttpClient buildClient() {
        String hostName = "127.0.0.1";
        int port = 3128;
        SocketConfig socketConfig = SocketConfig.custom()
                .setSoTimeout(3000)
                .setSoKeepAlive(false)
                .setSoReuseAddress(false)
                .build();
        HttpHost proxy = new HttpHost(hostName, port);
        return HttpClientBuilder.create()
                .setDefaultSocketConfig(socketConfig)
                .setProxy(proxy)
                .build();
    }

总结2:那些不变的,耗时的,不能创建太多的,不希
望被回收的对象都要创建成static的。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据引用[1]所述,ImageCrawler是一款基于Java的针对网站的图片爬虫程序,可根据关键词查询并批量下载图片。因此,Java中可以使用ImageCrawler来实现根据关键词搜索图片的功能。 以下是一个使用ImageCrawler实现根据关键词搜索图片并下载的Java代码示例: ```java import java.io.File; import java.io.IOException; import java.net.URL; import java.util.List; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.github.abola.crawler.CrawlerPack; import com.github.abola.crawler.extractor.Extractor; import com.github.abola.crawler.extractor.impl.JsoupExtractor; import com.github.abola.crawler.extractor.impl.RegexExtractor; import com.github.abola.crawler.extractor.impl.StringExtractor; import com.github.abola.crawler.extractor.impl.XPathExtractor; import com.github.abola.crawler.handler.CrawlerHandler; import com.github.abola.crawler.handler.CrawlerHandlerChain; import com.github.abola.crawler.handler.impl.DefaultCrawlerHandlerChain; import com.github.abola.crawler.handler.impl.DownloadHandler; import com.github.abola.crawler.handler.impl.FileHandler; import com.github.abola.crawler.handler.impl.ImageHandler; import com.github.abola.crawler.handler.impl.JsonHandler; import com.github.abola.crawler.handler.impl.TextHandler; import com.github.abola.crawler.handler.impl.XmlHandler; import com.github.abola.crawler.parser.Parser; import com.github.abola.crawler.parser.impl.JsoupParser; import com.github.abola.crawler.parser.impl.RegexParser; import com.github.abola.crawler.parser.impl.StringParser; import com.github.abola.crawler.parser.impl.XPathParser; import com.github.abola.crawler.pipeline.Pipeline; import com.github.abola.crawler.pipeline.impl.ConsolePipeline; import com.github.abola.crawler.pipeline.impl.FilePipeline; import com.github.abola.crawler.pipeline.impl.ImagePipeline; import com.github.abola.crawler.pipeline.impl.JsonPipeline; import com.github.abola.crawler.pipeline.impl.TextPipeline; import com.github.abola.crawler.pipeline.impl.XmlPipeline; import com.github.abola.crawler.scheduler.Scheduler; import com.github.abola.crawler.scheduler.impl.DefaultScheduler; import com.github.abola.crawler.selector.Selector; import com.github.abola.crawler.selector.impl.CssSelector; import com.github.abola.crawler.selector.impl.JsoupSelector; import com.github.abola.crawler.selector.impl.RegexSelector; import com.github.abola.crawler.selector.impl.XPathSelector; import com.github.abola.crawler.util.CrawlerUtil; import com.github.abola.crawler.util.FileUtil; import com.github.abola.crawler.util.ImageUtil; import com.github.abola.crawler.util.JsonUtil; import com.github.abola.crawler.util.StringUtil;import com.github.abola.crawler.util.XmlUtil; public class ImageCrawlerDemo { public static void main(String[] args) throws IOException { String keyword = "java"; // 设置搜索关键词 String savePath = "D:/images/"; // 设置图片保存路径 // 创建ImageCrawler对象 ImageCrawler crawler = new ImageCrawler(keyword, savePath); // 开始爬取图片 crawler.crawl(); } } // ImageCrawler类 class ImageCrawler { private String keyword; // 搜索关键词 private String savePath; // 图片保存路径 public ImageCrawler(String keyword, String savePath) { this.keyword = keyword; this.savePath = savePath; } public void crawl() throws IOException { // 构造搜索URL String searchUrl = "https://www.google.com/search?q=" + keyword + "&tbm=isch"; // 发送HTTP请求并获取响应内容 Document doc = Jsoup.connect(searchUrl).get(); // 解析响应内容,获取所有图片元素 Elements imgElems = doc.select("img"); // 遍历所有图片元素,下载图片 for (Element imgElem : imgElems) { // 获取图片URL String imgUrl = imgElem.attr("src"); // 下载图片 ImageUtil.downloadImage(imgUrl, savePath); } } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值