简体   繁体   English

如何让我的构造函数同步?

[英]How I can make my constructor synchronized?

I have a class. 我上课了。

public CarSold{

static int count;

CarSold(){count++;}


// Other code
}

Now this is running in multithreading enviroment. 现在这是在多线程环境中运行的。 And I read here that constructors are not implicitly syncronized. 在这里读到构造函数不是隐式同步的。

In that case, there is a chance that I don't have the correct count of cars sold in the count variable. 在这种情况下,我可能没有在count变量中销售正确数量的汽车。

What is the way to make sure that it has a correct count? 有什么方法可以确保它具有正确的计数?

I can think of 2 ways. 我可以想到两种方式。

  1. Class level locking inside the constructor using synchronized(CarSold.class) 使用synchronized(CarSold.class)在构造函数内部进行类级别锁定
  2. I can use AtomicInteger. 我可以使用AtomicInteger。

Can this 2 approach solves the problem ? 这两种方法可以解决这个问题吗? And is there is any other way? 还有其他方法吗?

Thanks. 谢谢。

You don't synchronize a constructor, that doesn't make any sense semantically, you synchronize the access to the variable. 您没有同步一个构造函数,在语义上没有任何意义,您同步对变量的访问。 Which can happen from anywhere that has access to it. 这可能发生在任何可以访问它的地方。

What you are looking for in this case is AtomicInteger . 在这种情况下,您正在寻找的是AtomicInteger

"Now this is running in multithreading enviroment. And I read here that constructors are not implicitly syncronized."

You might have already got the logic but just wanted to mention it again. 你可能已经有了逻辑但只是想再次提及它。 When you synchronize a method, may it be constructor, it creates lock on 'this' object which is still not initialized and null in case if you are trying to synchronize the constructor. 同步方法时,可能是构造函数,它会对“this”对象创建锁定,该对象仍未初始化,如果您尝试同步构造函数则为null。 But You can create a separate instance object and use a lock on that object. 但是您可以创建单独的实例对象并对该对象使用锁定。 Chances are the instance variable you are trying to use as lock is also not yet initialized. 机会是您尝试使用的实例变量,因为锁尚未初始化。 In that case you will get NP exception. 在这种情况下,您将获得NP异常。 Now, important thing is from Java 6 final instance variables are thread safe so use can use a final object for locking in constructor. 现在,重要的是从Java 6最终实例变量是线程安全的,因此使用可以使用最终对象来锁定构造函数。

If you are locking on XYD.class it will be application wise lock which might be valid in your case but sometimes you need instance level lock and in that case you can use above approach. 如果您在XYD.class上锁定它将是应用程序智能锁定,这可能在您的情况下有效,但有时您需要实例级别锁定,在这种情况下,您可以使用上述方法。

Can this 2 approach solves the problem ?

Yes. 是。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM