我正在尝试将count
变量与get
同步,并使用私有帮助函数进行基于其他成员的设置。多个线程分别调用setCount()
deadlineNoteVisible
并referencesAvailable
更改。
只有synchronized
方法使用setCount()
,一切正常,但当我向synchronized(this)
电话添加get()
时,我
得到:
OutOfMemoryError: Failed to allocate a 57993496 byte allocation with 16764448 free bytes and 32MB until OOM
代码(用Kotlin编写):
var count: Int = 0
// Why does adding synchronized here explode?
get() = synchronized(this) { count }
private set
private fun setCount() {
synchronized(this) {
count = 0
if (deadlineNoteVisible) {
count += 1
}
if (referencesAvailable) {
count += 1
}
}
}
堆栈追踪:
Error reporting crash
java.lang.OutOfMemoryError: Failed to allocate a 57993496 byte allocation with 16764448 free bytes and 32MB until OOM
at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:95)
at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:125)
at java.lang.StringBuffer.append(StringBuffer.java:278)
at java.io.StringWriter.write(StringWriter.java:123)
at com.android.internal.util.FastPrintWriter.flushLocked(FastPrintWriter.java:358)
at com.android.internal.util.FastPrintWriter.appendLocked(FastPrintWriter.java:303)
at com.android.internal.util.FastPrintWriter.write(FastPrintWriter.java:625)
at com.android.internal.util.FastPrintWriter.append(FastPrintWriter.java:658)
at java.io.PrintWriter.append(PrintWriter.java:691)
at java.io.PrintWriter.append(PrintWriter.java:687)
at java.io.Writer.append(Writer.java:198)
at java.lang.Throwable.printStackTrace(Throwable.java:324)
at java.lang.Throwable.printStackTrace(Throwable.java:300)
at android.util.Log.getStackTraceString(Log.java:343)
at com.android.internal.os.RuntimeInit.Clog_e(RuntimeInit.java:61)
at com.android.internal.os.RuntimeInit.-wrap0(RuntimeInit.java)
at com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:86)
at com.crashlytics.android.core.CrashlyticsUncaughtExceptionHandler.uncaughtException(CrashlyticsUncaughtExceptionHandler.java:249)
at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)
答案 0 :(得分:5)
实际上,您有一个StackOverflowError
,因为您无条件地从getCount()
致电getCount()
。我想这只是一个错字,代码应该是:
var count: Int = 0
get() = synchronized(this) { field }
private set
此处的field
标识符允许您访问该属性的支持字段。您可以阅读有关支持字段here的更多信息。