是java/kotlin中的文件线程安全吗
我在Kotlin中有一个文件实例,该实例是本地的。我只想知道多个线程/共同路线是否可以同时访问此文件实例并写入它。输出文件中缺少一些行,这可能是原因。
由于文件实例是本地的,因此每个线程/共同访问都应该具有自己的实例,并且不应存在这样的问题IMO。
private val noOfThreads = newFixedThreadPoolContext(nThreads = 3, name = "coRoutineThreads")
val nameOfFile = "test.csv"
fun coRoutineFunction(){
runBlocking{
for(i in 1..100)
{
async(noOfThreads){
writeToFile(nameOfFile)
}
}
}
}
fun writeToFile(nameOfFile){
val file = File(fileName)
//write to file using bufferedWriter and CSVPrinter
}
原始的writetofile将使文件名和数据添加到文件中。如果不存在文件,它将创建新文件,否则将附加。
internal fun writeToFile(fileName: String, recordList: List<Map<String, String>>) {
try {
val file = File(fileName)
if (!file.exists()) {
file.createNewFile()
val writer = FileWriter(file)
val bufferedWriter = BufferedWriter(writer)
writeCSVRecordWithHeader(bufferedWriter, recordList)
bufferedWriter.close()
} else {
val writer = FileWriter(file, true)
val bufferedWriter = BufferedWriter(writer)
concCSVRecord(bufferedWriter, recordList)
bufferedWriter.close()
}
} catch (exception: Exception) {
logger.error("Exception at writeRecordsToFile while creating file: ${ExceptionUtils.getStackTrace(exception)}")
throw exception
}
I have a File instance in Kotlin which is local. I just want to know whether multiple threads/co-routines can access this file instance at the same time and write to it. There are some lines missing from the output file, and that may be the reason.
As the file instance is local, each thread/co-routine it should have it's own instance, and there should not be such a problem IMO.
private val noOfThreads = newFixedThreadPoolContext(nThreads = 3, name = "coRoutineThreads")
val nameOfFile = "test.csv"
fun coRoutineFunction(){
runBlocking{
for(i in 1..100)
{
async(noOfThreads){
writeToFile(nameOfFile)
}
}
}
}
fun writeToFile(nameOfFile){
val file = File(fileName)
//write to file using bufferedWriter and CSVPrinter
}
The original writeToFile, will get the fileName and data to be added to the file. If file does not exist, it will create new file, otherwise it will append.
internal fun writeToFile(fileName: String, recordList: List<Map<String, String>>) {
try {
val file = File(fileName)
if (!file.exists()) {
file.createNewFile()
val writer = FileWriter(file)
val bufferedWriter = BufferedWriter(writer)
writeCSVRecordWithHeader(bufferedWriter, recordList)
bufferedWriter.close()
} else {
val writer = FileWriter(file, true)
val bufferedWriter = BufferedWriter(writer)
concCSVRecord(bufferedWriter, recordList)
bufferedWriter.close()
}
} catch (exception: Exception) {
logger.error("Exception at writeRecordsToFile while creating file: ${ExceptionUtils.getStackTrace(exception)}")
throw exception
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论