[英]Is this instance created only once in my example?
I have the following code.我有以下代码。 In the other class, I tried to create the
S3ClientClass2
object as val s3 = new S3ClientClass2()
.在另一个 class 中,我尝试将
S3ClientClass2
object 创建为val s3 = new S3ClientClass2()
。 After creating the s3, then calling the readFromS3
method for every single request.创建 s3 之后,然后为每个请求调用
readFromS3
方法。 In this scenario, I am wondering that the amazonS3Client
is created only once or created many times for every request.在这种情况下,我想知道
amazonS3Client
是只创建一次还是为每个请求创建多次。 I think that is is created only once.我认为这是只创建一次。 Is this right?
这是正确的吗?
class S3ClientClass2 {
lazy val amazonS3Client = this.getS3Client()
private def getS3Client() = {
AmazonS3ClientBuilder
.standard()
.withRegion(Regions.AP_NORTHEAST_1)
.build()
}
def readFromS3(s3Bucket: String, filepath: String): String = {
var s3object: S3Object = null
try {
s3object = amazonS3Client.getObject(s3Bucket, filepath)
readFromS3(s3object)
}
finally {
if (s3object != null) {
s3object.close()
}
}
}
def readFromS3(obj: S3Object): String = {
val reader = new BufferedReader(new InputStreamReader(obj.getObjectContent))
reader.lines().collect(Collectors.joining())
}
}
yes, lazy val
is initialised only once when it is first used.是的,
lazy val
在第一次使用时只初始化一次。 That means, the first time you use amazonS3Client
the getS3Client
method will be called, every subsequent usage of amazonS3Client
will use the cached value.这意味着,第一次使用
amazonS3Client
时,将调用getS3Client
方法,随后每次使用amazonS3Client
时,都将使用缓存的值。
Some other hints.其他一些提示。 You are mixing in Java stuff in
readFromS3(obj: S3Object)
method for no good reason, it could be easily rewritten to pure Scala:您无缘无故在
readFromS3(obj: S3Object)
方法中混合了 Java 内容,它可以很容易地重写为纯 Scala:
def readFromS3(obj: S3Object): String = {
scala.io.Source.fromInputStream(obj.getObjectContent).mkString
}
Regarding readFromS3(s3Bucket: String, filepath: String)
, you should never used null
in scala, if you are working with something that might or might not have a value see Option
, for things that might crash with some error see scala.util.Either
and scala.util.Try
.关于
readFromS3(s3Bucket: String, filepath: String)
,你不应该在 scala 中使用null
,如果你正在处理可能有或可能没有值的东西,请参阅Option
,对于可能因某些错误而崩溃的东西,请参阅scala.util.Either
和scala.util.Either
scala.util.Try
。 Also, what is the expected behaviour of this function when exception is thrown in the try
block?此外,当
try
块中抛出异常时,此 function 的预期行为是什么? In the current design it will rethrow it and escalate up your call stack.在当前的设计中,它将重新抛出它并升级您的调用堆栈。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.