Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set timeout to Lock mechanism?

I have a global variable(object) named X. Also i have two different thread named ThreadA and ThreadB which uses the X at the same time.

ThreadA add +1 for 100 times and ThreadB multiplies with 2 for two times.

When i started them at the same time, concurrency occurs and i saw something

1
2
3
6
7
14.. etc

i already solved this problem by adding

ReentrantLock  lock = new ReentrantLock();
lock.lock();
..
lock.unlock();

mechanism.

Now my code works

1
2
3
4
...
100
200
400

But i want to add timeout so if ThreadA takes more than 2 seconds,want to release lock so ThreadB can manipulate it.

Want to see something like

1
(wait 100ms)
2
(wait 100ms)
3
...
20
400
800
801
( wait 100ms)
802
...

I already tried trylock(2000,TimeUnit.MILLISECONDS) but it decides only entering time.

like image 935
O. Kumru Avatar asked Jan 01 '26 00:01

O. Kumru


1 Answers

That kind of functionality doesn't exist and for good reason. It would be inherently unsafe to release a lock based on time alone, with no regards to the internal state that the lock is supposed to protect.

Whereas a timeout for acquiring a lock makes sense, having a timeout for the duration of the lock would cause more trouble than it would be of use. Once you've acquired the lock, you can do whatever you want until you decide to release it. If you get a deadlock (a situation that could get some use from a timed lock) that's unfortunate, but it's solved by fixing your design instead of setting timeouts on locks.

As your code is just general threading test code I guess you were just assuming that such a mechanism exists, but if you can come up with a situation where you'd need something like that, it can probably be coded in a different way.

like image 80
Kayaman Avatar answered Jan 04 '26 02:01

Kayaman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!