Lock.tryLock(): Thread performing different tasks? [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am trying to understand multi-threading in Java, using the
features which were added as part of java.util.concurrent.* . To begin with, there is concept of lock which a thread can try to acquire; if a thread can't acquire, it can do some other tasks.
This I have read in online materials as well in some books, but never ever seen anything they have implemented in real. How is this possible that if a thread can't acquire a lock it can execute other tasks; isn't a thread supposed to do a single "piece of work"? How can it have multiple logic execution based on if it can/can't acquire a lock?
Is there any real implementation which I can refer to see to understand, to reinforce the concepts; else it seems too abstract, how to implement in real life.
Any explanations?

It's difficult to find real life examples because normally you wouldn't design your software to use tryLock(). The example given in the javadoc is as follows:
Lock lock = ...;
if (lock.tryLock()) {
try {
// manipulate protected state
} finally {
lock.unlock();
}
} else {
// perform alternative actions
}
But you wouldn't design your software like that, would you? What if the lock is never (or almost never) available, how will that affect your program? What if it's always available? You have a method that does one of two things depending on pure chance. That's not good design, it increases randomness and complexity.
Okay, so it's not something you decide to use because it's elegant. What is it good for?
Imagine you've inherited a legacy project designed by an insane programmer and it has severe issues with deadlocks. It has synchronized methods peppered all around and needs to be booted at least once every week because it locks up. First you convert all the synchronized methods to use Lock instead. Now you no longer block forever on synchronized, but can use tryLock(long, TimeUnit) to timeout and prevent deadlocks.
Now you've solved the reboot causing deadlocks, but it's still not optimal since you're spending time waiting. With additional refactoring you manage to reduce the locks, but unfortunately you can't do proper lock ordering just yet. Your end code looks like this, where inner locks are acquired with tryLock() or outerlock is released to prevent deadlock:
Lock outerLock = ...;
outerLock.lock(); // Here we block freely
try {
Lock innerLock = ...;
if (innerLock.tryLock()) { // Here we risk deadlock, we'd rather "fail-fast"
try {
doSomethingProtectedByLocks();
} finally {
innerLock.unlock();
}
} else {
throw new OperationFailedException(); // Signal the calling code to retry
}
} finally {
outerLock.unlock();
}
I think the problem is mainly with wording. The Javadoc talks about "actions" (like unlocking an outer lock) being performed based on whether the lock was acquired or not, but it's easy to read it as if the thread would have 2 separate responsibilities determined by the lock state.

Related

How does synchronization work in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
is the following statement correct:
" There shouldn't be any thread interference between two synchronized methods in 2 different classes . So they can run concurrently without any problems."
Thanks for your time
That is way too vague. A few pointers:
"how does synchronization work in Java": There are a couple of mechanisms, the question seems to be about the synchronized keyword. This works by marking "critical sections" that must not be executed by more than one thread at the same time, and having the threads "lock" a monitor object while they are in that section (so that all other threads wait).
synchronized methods synchronize on the object instance (or class object in case of a static method). So methods in different classes do not synchronize with each-other that way. They will run concurrently.
you can use the synchronized keyword to synchronize blocks on any other monitor object. This way, methods in different classes can still be synchronized with each-other.
"can run concurrently without problems" is not guaranteed just by having some synchronization (or lack thereof). You need to see what mutable state these methods (directly or indirectly) try to access (and who else does the same) to see what kind of concurrency control is necessary.
You misunderstood the concept a little bit. Collisions happen when two (or more) threads simultaneously try to make a change on the same data or when one of them tries the read the data while the other thread is trying to change it.
When two thread tries to change the shared resource simultaneously, a race condition occurs. Check out this link to learn more about Race Condition.
In order to prevent this kind of problems, you need to guard the shared resource for simultaneous changes. Mutexes and semaphores are invented for this purpose: To lock the shared resource for the other threads, when one thread is currently making a change on it. For this purpose, Java uses the synchronized keyword. You can read more about Synchronized in Java using the link.
Note that, using the synchronized keyword will not eliminate all of the synchronization related issues, but it is a good starting point.

What do the terms synchronized and thread-safe mean? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I've been watching a lot of videos on data structures, and these terms are always being mentioned: synchronized/not synchronized and thread-safe/not thread-safe.
Can someone explain to me in simple words what synchronized and thread-safe mean in Java? What is sync and what is thread?
A thread is an execution path of a program. A single threaded program will only have one thread and so this problem doesn't arise. Virtually all GUI programs have multiple execution path and hence threads - one for processing the display of the GUI and handing user input, others for actually performing the operations of the program. This is so that the UI is still responsive while the program is working.
In the simplest of terms threadsafe means that it is safe to be accessed from multiple threads. When you are using multiple threads in a program and they are each attempting to access a common data structure or location in memory several bad things can happen. So, you add some extra code to prevent those bad things. For example, if two people were writing the same document at the same time, the second person to save will overwrite the work of the first person. To make it thread safe then, you have to force person 1 to wait for person 2 to complete their task before allowing person 1 to edit the document.
Synchronized means that in a multiple threaded environment, a Synchronizedobject does not let two threads access a method/block of code at the same time. This means that one thread can't be reading while another updates it.
The second thread will instead wait until the first is done. The overhead is speed, but the advantage is guaranteed consistency of data.
If your application is single threaded though, Synchronized has no benefit.
As per CIP:
A class is thread-safe if it behaves correctly when accessed from
multiple threads, regardless of the scheduling or interleaving of the
execution of those threads by the runtime environment, and with no
additional synchronization or other coordination on the part of the
calling code.
So thread safety is a desired behavior of the program in case it is accessed by multiple threads. Using the synchronized block is one way of achieving that behavior. You can also check the following:
What does 'synchronized' mean?
What does threadsafe mean?

Preventing infinite loop in java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I wanted to make a little game like robot wars in Java.
the idea is to extend my class Robot, with the custom rules, you add to it.
however, i have so things I want to prevent coders to do, like infinite loops.
I know some compilers will complain if there is an endless loop, in a Methode the requires a returning value. but I don't think all compilers will return an error on this, so I was thinking if there was a way to check this another way too?
or maybe a way to make some sort of timeout on a method?
Update:
Looking back to this question I posted almost 3 and a half year ago, I am no longer doing programming in Java, however still an active Programmer, and with the years, I learned how hard it is to police 3rd party code if there is no review cycle implemented.
There is no simple way to check if Code is malicious (that is why we have anti-virus programs).
To do a thing that I wanted to do, I first of need to control the entire platform I am developing too, to check for reasons the code is behaving as it is, a task that would be nearly imposable or too time-consuming.
that is why to do this more securely, the solution I reached is to use a Scripting Language that limits the user to the idea you had in mind.
Hosting a Program on servers, that everybody has access to add code to is simply not a good idea. not even with Manage Program Languages as Java and CIL, as the platforms are not checking for those specifics, it would simply take too much effort to do this.
Even though there is a way to "Sandbox" programs in Java, by using Policies
and C# have something similar, it would never prevent a skilled programmer to exploit or do something that was never intended.
I hope this update gives other a warning to what they are doing since I noticed this topic recently go searched a lot.
I'm not sure I understand the context of the game. But I would like to begin this answer by saying that you cannot prevent someone from coding an infinite loop, and you cannot stop an infinite loop once it is running. As long all your code is reachable, and you return what you have to etc., Java won't help you in detecting and preventing infinite loops.
However, if you would like to execute another routine for a period of time and ensure you get access to your thread again, one way to do so is through a Future.
If you allow "other coders" to implement a Runnable or a Callable, then you can use the Future class's get(long timeout, TimeUnit unit) method to cause the robot to timeout after a predetermined period of time. This will prevent infinite loops in the other thread from claiming your thread forever.
However, it is important to note that if the other Robot has an infinite loop, it may never stop running even after your timeout. Java provides no guarantee that it can stop the other thread. So when invoking such routines in your code, it is important that you know what you're invoking.
Here is some sample code which uses a Future.
abstract class Robot implements Runnable {
}
class SampleRobot extends Robot {
#Override
public void run() {
while (!Thread.interrupted()) {
}
}
}
class RobotRunner {
ExecutorService executorService = Executors.newSingleThreadExecutor();
public void runRobot(Robot robotToRun) throws InterruptedException, ExecutionException {
Future<?> robotFuture = executorService.submit(robotToRun);
try {
robotFuture.get(5, TimeUnit.SECONDS);
} catch (TimeoutException e) {
// This is where you would handle the timeout occurring.
}
}
}
Remember that you should not expect real-time behavior from timeouts in Java. Also remember to shutdown your ExecutorService when you're done using it.

Java Synchronization [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
What is this:
synchronized (this) {
// ...some code...
}
good for?
(Could you write an example?)
It prevents concurrent access to a resource. Sun's got a pretty good description with examples.
It prevents multiple threads from running the code contained within the braces. Whilst one thread is running that code, the remainder are blocked. When the first thread completes, one of the blocked threads will then run the synchronised code, and so on.
Why do you want to do this ? The code within the block may modify objects such that they're in an inconsistent state until the blocks exits. So a second thread coming in would find inconsistent objects. From that point on chaos ensues.
An example would be removing an object from one pool and inserting it in another. A second thread might run whilst the first thread is moving the object, and subsequently find the object referenced in both collections, or neither.
You can also use this mechanism to restrict multiple threads from accessing a resource designed to be used by one resource (e.g. a trivial database, for example).
Note that the following two are equivalent:
synchronized void someMethod() {
// ...
}
and
void someMethod() {
synchronized (this) {
// ...
}
}
From the now-defunct Java Quick Reference formerly at http://www.janeg.ca/scjp/threads/synchronized.html:
Synchronizing threads has the effect
of serializing access to blocks of
code running on the thread.
Serializing in this context means
giving one thread at a time the right
to execute specific block of code.

Implementing a global lock in Java

I have a relatively simple (perhaps stupid) question regarding synchronisation in Java.
I have synchronisation blocks that acquire locks on various objects throughout my code. In some scenarios, I want to acquire a global lock that subsumes every other synchronisation statement in my code.
Is there a fancy way to do this in Java without re-writing all the current synchronisation code?
For example,
Thread t1
synchronized (o1)
{
synchronized (o2)
{
// ...
}
}
Thread t2
synchronized (global_lock)
{
// ...
}
When thread t2 is inside the synchronised block, thread t1 should not be allowed to acquire the locks on o1 and o2.
Many thanks
if
It's not possible;
It's a really bad idea ( sorry ).
It's deadlock-prone, since it forces you to have a pre-determined locking order for all locks, no matter where they are.
Usually it's a good idea, if you need to acquire two locks, to always have a predetermined order:
synchronized(LOCK1) {
synchronized(LOCK2) {
}
}
But a global lock would need some sort of protocol - a global aquisition order - for all the locks. And that may not be possible at all. Most locks guard specific, self-contained, critical sections. They would be unaware that someone would 'yank' them out and aquire them and therefore would not be written to handle this situation.
So it's not possible, and you should be happy it's not. Although it seems to be the easy way out, it would bring a lot of pain.
Leaving aside the sheer horror of what you are proposing, you may want to consider using Aspect Oriented Programming (AOP) to "weave" additional synchronization/locking into your code at run time. You should be able to do this without writing the source.
There are many AOP options, including AspectJ and Spring AOP, which may be suitable depending on your environment.
The only feasible way to do it would be actually parse/modify/save (automatically) all the code. I did something like this for a project recently and it worked pretty good. We can talk more if you are interested.

Categories