我正在寻找类似于这种语法的东西,即使它不存在.
我希望有一个方法作用于集合,并且在方法的生命周期中,确保集合不会被搞乱.
这可能看起来像:
private void synchronized(collectionX) doSomethingWithCollectionX() {
// do something with collection x here, method acquires and releases lock on
// collectionX automatically before and after the method is called
}
但相反,我担心这样做的唯一方法是:
private void doSomethingWithTheCollectionX(List> collectionX) {
synchronized(collectionX) {
// do something with collection x here
}
}
这是最好的方法吗?