Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why synchronized method is not included in interface

When I use synchronized on a method in an interface, the compiler emits an error. Can you tell me why this happens?

What is the reason (logically) that synchronized cannot be applied to a method on an interface?

I tried to make an Interface over Threadpool in this link. Help me to make Interface in my above code.

like image 493
devsda Avatar asked Jan 25 '13 11:01

devsda


People also ask

Why is synchronized not working in Java?

Java synchronisation only works if the object is locked by all threads. If the java threads are locks for different instances of class objects, then the synchronisation will not work. All java threads should try to lock the same object, and if the lock is not available, the thread will wait until the lock is released.

Why are locks better than synchronized?

Lock framework works like synchronized blocks except locks can be more sophisticated than Java's synchronized blocks. Locks allow more flexible structuring of synchronized code.

Can a class have both synchronous and non synchronized methods?

Yes, they can run simultaneously both threads.

Can we use synchronized in main method?

There is nothing that says the main function can only be used as the entry point to a program. Being static, there is no reason other classes couldn't call SynchronisizedMain. main() . Being synchronized prevents multiple instances from being executed concurrently which might be desirable.


1 Answers

Because synchronized is an implementation detail. One implementation of the method might need to make the method synchronized, whereas another one might not need it. The caller doesn't care whether the method is synchronized or not. It's not part of the contract, which tells what the method does. Which synchronization technique, if any, is used to fulfill the contract is irrelevant.

like image 177
JB Nizet Avatar answered Sep 21 '22 09:09

JB Nizet