简体   繁体   中英

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.

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.

Java provides Condition class to achieve similar functionality. You use await() method of condition class with time of 2 seconds and else call lock.unlock(). Though remember, the wait time might be larger than 2 seconds as well due to inherent nature of threads. Also, this will be error prone and you will need to be careful about different cases. Refer the docs: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Condition.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM