It knows simply because it’s a compensation event linked to a compensation task.
So if you throw a compensation and that task has been completed the corresponding compensation event will trigger the compensation task.
Also if you want to add a java class - convert it to a service task.