1

Can synchronized be used for some of the code blocks written in lambda expression block. With respect to the following code snippet :

workflowTasks.forEach((workflowTask) -> {
        String taskName = workflowTask.getTaskName();
        if (profileNames.containsKey(taskName) || newSetDuplication.contains(taskName)) {
            errorMessages.append(taskName + ",");
        }
        newSetDuplication.add(taskName);
    });
Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
Mithun Theertha
  • 131
  • 2
  • 6
  • 6
    The lambda expression block allows all statements an ordinary code block allows too. The bigger question is whether it makes sense. – Holger Mar 01 '18 at 16:08

1 Answers1

2

Of course! Your block of code is logically equivalent to the following, assuming workFlowTask is of the type WorkFlowTask:

for (WorkFlowTask workFlowTask : workFlowTasks) {
    String taskName = workflowTask.getTaskName();

    if (profileNames.containsKey(taskName) || newSetDuplication.contains(taskName)) {
        errorMessages.append(taskName + ",");
    }

    newSetDuplication.add(taskName);
}

Obviously, the synchronized keyword can be used here, although there are many other things to consider before using it, especially within a loop. Your forEach lambda is just syntactic sugar for a Consumer<WorkFlowTask> anyway, which you can also use synchronized with.

Jacob G.
  • 28,856
  • 5
  • 62
  • 116
  • Just to add a small note: `this` in a lambda references the instance of the surrounding class. So, the `synchronized` block in the lambda does not synchronize an instance of the functional interface, which is why using `synchronized` should not have any undesired side effects. https://stackoverflow.com/a/24202272/1482294 – rosetree Jan 12 '21 at 14:52