Could sync annotation?

Would it be bad if instead of the synchronized we had the @Synchronized annotation? It would be more natural to annotate in this case (because you can override the synchronized method using an unsynchronized method - thus, synchronized does not say anything about the method itself, but rather indicates something in addition to the method (that the method is protected in a certain way), so this is not really a keyword?)

+4
source share
4 answers

Synchronized conversion almost directly to monitorenter / monitorexit at the byte code level. And you indicate that synchronize, you cannot do it with annotation:

 synchronized (myLock) { } 

Thus, it is clear to me that this is a keyword.

+2
source

synchronized is used for code blocks, and you cannot add annotation to a code block.

You may have @synchronized on methods or even classes, but Java does not support annotations when Java was first introduced.

I find it important enough to deserve my keyword .;)

+4
source

It would be great, but annotation cannot completely replace the synchronized : there are synchronized blocks that cannot be marked with annotation.

In addition, the synchronized unit receives the monitor used for synchronization. It can be delivered dynamically, which gives us some flexibility. Annotations do not allow this, since all parameters must be provided at compile time.

+2
source

Perhaps as a version of the synchronization method, yes. But another use of synchronization allows you to specify the monitor to which you are synchronizing.

 public void someMethod() { synchronized(this) { //sync code } //unsynced code. } 
+1
source

Source: https://habr.com/ru/post/1435095/


All Articles