FreeMarker 在使用Pipe IO 时进程僵死

因为在编写时疏忽,而使程序僵死,后来才发现是因为 PipeWriter 和 Reader的原因,导致 template.Process 僵死。

如下代码就会这样。


cfg=new Configuration(Configuration.VERSION_2_3_21);
cfg.setDefaultEncoding("utf-8");
cfg.setDirectoryForTemplateLoading(new File("template"));

PipedWriter pw = new PipedWriter();
Reader reader = new PipedReader(pw);
Template tpl=cfg.getTemplate("xxxx.tpl");
Map map....
map.put(.....);
..........
tpl.process(map, pw);   //在此处线程暂停了
pw.close();

//这里需要另起一个线程用于reader 读取数据
doProcess(reader);

其实原因就是 Pipe 缓冲区满了,tpl.process处理的时候暂停了。所以把程序改一下,增加一个后台线程来处理Freemarker的tpl.process 就可以了。 很简单。

例如:把 template.process放入子线程也可以,write也在子线程中关闭。

reader=.....
pw=.......
Thread th=new Runnable(){
    public void Run()
        {
            tpl.process(map, pw);
            pw.close();                                
        }
}
th.start();

while(reader.readLine()!=null)
{
    ...........
}
reader.close();

转载于:https://my.oschina.net/33876402/blog/725981

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值