# Unity [Java] Wait() / Notify() order of execution: The placement of these two methods are different from common examples.

This topic is 2303 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Here's a working non-deadlock code of having four threads running the same Runnable method.
[source lang="java"]
package concept;

//Generic Process
public class GenericProcess implements Runnable
{
private int number;

public Object lock;

public GenericProcess setValue(int value)
{
number = value;
return this;
}

public GenericProcess(Object obj)
{
lock = obj;
}

@Override
public void run()
{
while (true)
{
synchronized (lock)
{
lock.notify();
{
try
{
System.out.println(this.getClass() + " " + number + " has the lock.");
lock.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}

}

}
}

[/source]

I questioned the order of execution of both wait() and notify(). Some examples found by Googling place notify() underneath wait(); wait() executes first, then notify(). Some examples include boolean flags to detect execution, and also executes wait() first before notify().

Without any boolean flags or something to detect if the thread is executing during its quantum time frame, I forced myself to try making a small mutex that allows any threads to simply execute this while loop.

Am I doing it correctly, if compared to some Java concurrency guidelines which have a larger acceptence among the developer community? Why do people put notify() underneath wait() by some lines of code, by making notify() to appear near the end of synchronized methods or Object references? For the second question, why are they (the codes) be designed like that?

##### Share on other sites
What exactly is this code supposed to do? Racing to hold the lock doesn't make much sense and spinlocks are bad enough as it is.

##### Share on other sites

What exactly is this code supposed to do? Racing to hold the lock doesn't make much sense and spinlocks are bad enough as it is.

Good question. Today, I asked my classmate what our professor wants us to do. He said all I have to do is just calculate any kind of scheduling algorithms, like FCFS, Shortest Job First, or use Round-robin scheduling, depending on whether I do preemptive or nonpremptive. In short, I have no clue still. Ask 4 different classmates, and they all replied the same negative answer.

My code above was, not is (unsure of its status), about trying to schedule 4 threads running in 1 lock, to try and make all 4 threads to execute in specific order, like:

t1 -> t2 -> t3 -> t4.

I always get t2 -> t0 -> t1 -> t3, and repeat. If I were to place a scheduling scheme (don't know at the moment) in, it might run the 4 threads to execute in a fashionly order. That above was my basis (motive) to making this code to work, and I worked on it until I get the message that probably a large portion of the class have no clue on what our professor wants us to do.

If I don't try doing a spinlock, I supposely don't know how to force a thread to come out of the waiting state, and I'm still a beginner when it comes to Java synchronized programming. With the aid of Google, a lot of Java wait()/notify() articles and 5 hours to grind, my progress so far is just about it, that piece of code above is what I make most of my time into, from scratch.

What do I do with my 4 threads and this lock? Thanks in advance.

##### Share on other sites

He said all I have to do is just calculate any kind of scheduling algorithms, like FCFS, Shortest Job First, or use Round-robin scheduling

None of this has anything to do with threads. Schedulers are almost always single-threaded. Efficient concurrent schedulers are incredibly difficult to implement.

to try and make all 4 threads to execute in specific order, like: [/quote]

it might run the 4 threads to execute in a fashionly order.[/quote]

Trying to get non-deterministic, non-realtime OS to execute threads in specific order is a recipe for dead- or live-lock. First step with such problems is to build a DAG, perform topological sort, then progress by level. Most of this cannot be done by userland process since threading states and thread dependencies and lock information isn't readily available. Or, ignore OS scheduler and implement own scheduler that runs in single thread, which is what large majority of language interpreters and VMs does these days.

What do I do with my 4 threads and this lock?[/quote]Delete them.

Scheduling problem can be formulated like this:interface Job { bool execute_for(int duration); // returns true if it completed, false if more work is to be done int remaining(); // optional, not always known, returns amount of work left }Job could be a thread (nothing to do with Java Thread class), a process or some other resource.

The algorithm then looks like this: Job selectNext(List<Job> jobs); int getSliceFor(Job j); while (true) { Job next = selectNext(jobs); bool done = next.execute_for(getSliceFor(next)); if (done) jobs.remove(next); }
You now need to implement two methods. selectNext() chooses the next job to run.
getSliceFor() determines for how long a given job should run at most. That can be simple fixed value (100ms) or some advanced algorithm, which may take into account statistics of previous runs, priority, remaining work to be done, ...

In a real OS threads would keep on running and scheduler would interrupt them. Since such facilities aren't available, we simulate this behavior by having jobs stop by themselves (execute_for). This is still pre-emptive scheduling, we just simulate the difficult part.

For cooperative scheduling, executeFor would not be given time parameter, but list of Jobs. It would then call execute_for() itself. If a job decided to not do that, the system would hang. If it wouldn't do that in timely manner, system would become unresponsive. Difference is mostly in where the selectNext() gets called.

Round robin version: Job selectNext(List<Job> jobs) { Job next = jobs.remove(0); // remove first job jobs.add(next); // append it to end of list return next; } int getSliceFor(Job j) { return 100; }

Jobs take turns, each runs for predefined amount of time. If List<> passed into selectNext is LinkedList, the example has O(1) complexity, but main loop would still have O(n). These are details related to how List<Job> is implemented, they need to be addressed separately.

An implementation of such system could use the following definition:class JobX : implements Job { private int amount_left; private int hidden; public JobX() { amount_left = random(1, 200000); // random value between these values hidden = random(0, 5) == 0; // hidden jobs don't know how much time they need } bool execute_for(int duration) { amount_left -= duration; return (amount_left < 0); } int remaining() { return (hidden ? -1 : amount_left); } }

##### Share on other sites
I thank you for the amount of helpful tips from your post. I just can't stress myself from not thanking you enough.

Looks like I need to teach myself some other scheduling algorithms first, before heading towards making threads, or maybe I need to learn how to grasp a starting point in the area of new knowledge.

• 9
• 10
• 12
• 10
• 10
• ### Similar Content

• By khawk
Watch the latest from Unity.

• By GytisDev
Hello,
without going into any details I am looking for any articles or blogs or advice about city building and RTS games in general. I tried to search for these on my own, but would like to see your input also. I want to make a very simple version of a game like Banished or Kingdoms and Castles,  where I would be able to place like two types of buildings, make farms and cut trees for resources while controlling a single worker. I have some problem understanding how these games works in the back-end: how various data can be stored about the map and objects, how grids works, implementing work system (like a little cube (human) walks to a tree and cuts it) and so on. I am also pretty confident in my programming capabilities for such a game. Sorry if I make any mistakes, English is not my native language.
• By Ovicior
Hey,
So I'm currently working on a rogue-like top-down game that features melee combat. Getting basic weapon stats like power, weight, and range is not a problem. I am, however, having a problem with coming up with a flexible and dynamic system to allow me to quickly create unique effects for the weapons. I want to essentially create a sort of API that is called when appropriate and gives whatever information is necessary (For example, I could opt to use methods called OnPlayerHit() or IfPlayerBleeding() to implement behavior for each weapon). The issue is, I've never actually made a system as flexible as this.
My current idea is to make a base abstract weapon class, and then have calls to all the methods when appropriate in there (OnPlayerHit() would be called whenever the player's health is subtracted from, for example). This would involve creating a sub-class for every weapon type and overriding each method to make sure the behavior works appropriately. This does not feel very efficient or clean at all. I was thinking of using interfaces to allow for the implementation of whatever "event" is needed (such as having an interface for OnPlayerAttack(), which would force the creation of a method that is called whenever the player attacks something).

Here's a couple unique weapon ideas I have:
Explosion sword: Create explosion in attack direction.
Cold sword: Chance to freeze enemies when they are hit.
Electric sword: On attack, electricity chains damage to nearby enemies.

I'm basically trying to create a sort of API that'll allow me to easily inherit from a base weapon class and add additional behaviors somehow. One thing to know is that I'm on Unity, and swapping the weapon object's weapon component whenever the weapon changes is not at all a good idea. I need some way to contain all this varying data in one Unity component that can contain a Weapon field to hold all this data. Any ideas?

I'm currently considering having a WeaponController class that can contain a Weapon class, which calls all the methods I use to create unique effects in the weapon (Such as OnPlayerAttack()) when appropriate.

• Hi fellow game devs,
First, I would like to apologize for the wall of text.
As you may notice I have been digging in vehicle simulation for some times now through my clutch question posts. And thanks to the generous help of you guys, especially @CombatWombat I have finished my clutch model (Really CombatWombat you deserve much more than a post upvote, I would buy you a drink if I could ha ha).
Now the final piece in my vehicle physic model is the differential. For now I have an open-differential model working quite well by just outputting torque 50-50 to left and right wheel. Now I would like to implement a Limited Slip Differential. I have very limited knowledge about LSD, and what I know about LSD is through readings on racer.nl documentation, watching Youtube videos, and playing around with games like Assetto Corsa and Project Cars. So this is what I understand so far:
- The LSD acts like an open-diff when there is no torque from engine applied to the input shaft of the diff. However, in clutch-type LSD there is still an amount of binding between the left and right wheel due to preload spring.
- When there is torque to the input shaft (on power and off power in 2 ways LSD), in ramp LSD, the ramp will push the clutch patch together, creating binding force. The amount of binding force depends on the amount of clutch patch and ramp angle, so the diff will not completely locked up and there is still difference in wheel speed between left and right wheel, but when the locking force is enough the diff will lock.
- There also something I'm not sure is the amount of torque ratio based on road resistance torque (rolling resistance I guess)., but since I cannot extract rolling resistance from the tire model I'm using (Unity wheelCollider), I think I would not use this approach. Instead I'm going to use the speed difference in left and right wheel, similar to torsen diff. Below is my rough model with the clutch type LSD:
speedDiff = leftWheelSpeed - rightWheelSpeed; //torque to differential input shaft. //first treat the diff as an open diff with equal torque to both wheels inputTorque = gearBoxTorque * 0.5f; //then modify torque to each wheel based on wheel speed difference //the difference in torque depends on speed difference, throttleInput (on/off power) //amount of locking force wanted at different amount of speed difference, //and preload force //torque to left wheel leftWheelTorque = inputTorque - (speedDiff * preLoadForce + lockingForce * throttleInput); //torque to right wheel rightWheelTorque = inputTorque + (speedDiff * preLoadForce + lockingForce * throttleInput); I'm putting throttle input in because from what I've read the amount of locking also depends on the amount of throttle input (harder throttle -> higher  torque input -> stronger locking). The model is nowhere near good, so please jump in and correct me.
Also I have a few questions:
- In torsen/geared LSD, is it correct that the diff actually never lock but only split torque based on bias ratio, which also based on speed difference between wheels? And does the bias only happen when the speed difference reaches the ratio (say 2:1 or 3:1) and below that it will act like an open diff, which basically like an open diff with an if statement to switch state?
- Is it correct that the amount of locking force in clutch LSD depends on amount of input torque? If so, what is the threshold of the input torque to "activate" the diff (start splitting torque)? How can I get the amount of torque bias ratio (in wheelTorque = inputTorque * biasRatio) based on the speed difference or rolling resistance at wheel?
- Is the speed at the input shaft of the diff always equals to the average speed of 2 wheels ie (left + right) / 2?