Should objects in Java be static?

I know that in C #, when you have an object that you want to use as a lock for multithreading, you must declare it static inside the class, which will instantiate the class in a separate thread.

Is this also true for Java? Some examples online seem to declare the lock object as final ...

Edit: I have a resource that I want to limit to only one streaming access at a time. A class that extends the stream will be used to create multiple instances and run at the same time. What should i use?

Thanks.

+4
source share
3 answers

Depending on the context in which they should be used. If you want a lock on every instance, leave static away. If you want a lock for each class, use static . Also, keep it final .

+6
source

The simple answer is no. Long answer, it depends on what you want.

 private static final Object STATIC_LOCK = new Object(); private final Object lock = new Object(); public void doSomething() { synchronized (STATIC_LOCK) { // At most, one thread can enter this portion } synchronized (lock) { // Many threads can be here at once, but only one per object of the class } } 

With that said, I would recommend you take a look at the locks presented in java.util.concurrent.locks . Using java.util.concurrent.locks.Lock , you can do the following:

 Lock l = ...; l.lock(); try { // access the resource protected by this lock } finally { l.unlock(); } 
+3
source

Not

In Java, you can use non-static elements as locks.

 private Object lock = new Object(); public void test(){ synchronized (lock) { // your code } } 
+2
source

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


All Articles