What does 'synchronized' mean?

后端 未结 17 1908
广开言路
广开言路 2020-11-22 00:13

I have some questions regarding the usage and significance of the synchronized keyword.

  • What is the significance of the synchronized
17条回答
  •  滥情空心
    2020-11-22 00:38

    The synchronized keyword causes a thread to obtain a lock when entering the method, so that only one thread can execute the method at the same time (for the given object instance, unless it is a static method).

    This is frequently called making the class thread-safe, but I would say this is a euphemism. While it is true that synchronization protects the internal state of the Vector from getting corrupted, this does not usually help the user of Vector much.

    Consider this:

     if (vector.isEmpty()){
         vector.add(data);
     }
    

    Even though the methods involved are synchronized, because they are being locked and unlocked individually, two unfortunately timed threads can create a vector with two elements.

    So in effect, you have to synchronize in your application code as well.

    Because method-level synchronization is a) expensive when you don't need it and b) insufficient when you need synchronization, there are now un-synchronized replacements (ArrayList in the case of Vector).

    More recently, the concurrency package has been released, with a number of clever utilities that take care of multi-threading issues.

提交回复
热议问题