请教:关于RandomAccessFile阻塞ScheduledExecutorService的问题
大家好,我想实现 读一个正在动态增长的日志 的功能,下面第一段代码本够用了,可惜 那个日志还会不定时自动 归档(滚动,也就是 *.log 变 *.log1 ,*.log1变 *.log2 ,类推)
已经打开的 RandomAccessFile仍然盯着最早关联的文件,无法识别关联到新生成的 *.log,
所以我修改了这段代码,就是下面第二段代码
新的问题是:
程序已运行到 randomFile.close(); 处就卡住 ,不能进行了
想知道原因,我对多线程了解不多,请大家指点。谢谢了
final RandomAccessFile randomFile = new RandomAccessFile(logFile, "rw");
ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
exec.scheduleWithFixedDelay(new Runnable() {
public void run() {
try
{
RandomAccessFile randomFile = new RandomAccessFile(logFile, "rw");
randomFile.seek(lastTimeFileSize);
String tmp = "";
while ((tmp = randomFile.readLine()) != null)
{
//do something
}
}
catch (IOException e)
{
throw new RuntimeException(e);
}
ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
exec.scheduleWithFixedDelay(new Runnable() {
public void run() {
try
{
RandomAccessFile randomFile = new RandomAccessFile(logFile, "rw");
randomFile.seek(lastTimeFileSize);
String tmp = "";
while ((tmp = randomFile.readLine()) != null)
{
//do something
}
//程序会停止到这个位置,无法进行下去,没有报任何异常或错误
//如果把 close() 给删除掉,程序就可以正常往下运行了
randomFile.close();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
}, 0, 10, TimeUnit.SECONDS); 我想你的问题应该在这段代码的synchronized里面。
/**
* Closes this random access file stream and releases any system
* resources associated with the stream. A closed random access
* file cannot perform input or output operations and cannot be
* reopened.
*
* <p> If this file has an associated channel then the channel is closed
* as well.
*
* @exceptionIOExceptionif an I/O error occurs.
*
* @revised 1.4
* @spec JSR-51
*/
public void close() throws IOException {
synchronized (closeLock) {
if (closed) {
return;
}
closed = true;
}
if (channel != null) {
/*
* Decrement FD use count associated with the channel. The FD use
* count is incremented whenever a new channel is obtained from
* this stream.
*/
fd.decrementAndGetUseCount();
channel.close();
}
/*
* Decrement FD use count associated with this stream.
* The count got incremented by FileDescriptor during its construction.
*/
fd.decrementAndGetUseCount();
close0();
}
仔细想了下,问题不一定在close里面的同步哪儿。
我也没有理解透,求指点。
页:
[1]