Yes, a lambda expression can contain a synchronized block, but the synchronized keyword cannot be applied to the lambda itself the way it can to a method — you must synchronize explicitly on an object inside the lambda body.
Key Points: • Lambdas have no inherent lock object of their own, unlike instance methods which implicitly synchronize on `this`. • To synchronize inside a lambda, wrap the relevant code in a synchronized(lockObject) { ... } block within the lambda body. • The lock object is typically a field captured from the enclosing scope, so it must be final or effectively final. • For simple thread-safety needs, higher-level concurrency utilities like AtomicInteger, ConcurrentHashMap, or java.util.concurrent locks are often preferable to manual synchronized blocks in lambdas. • Overusing synchronized inside a lambda passed to a Stream or parallel stream can create contention and defeat the purpose of parallelism.
Example: A Runnable lambda that increments a shared counter could synchronize on a dedicated lock object: () -> { synchronized (lock) { counter++; } }.
Code Example:
private final Object lock = new Object();
private int counter = 0;
Runnable increment = () -> {
synchronized (lock) {
counter++;
}
};Interview Tip: A concise interview answer is:
"You can't put the synchronized keyword directly on a lambda the way you would on a method, because a lambda has no implicit lock object. Instead, I put a synchronized block inside the lambda body around an explicit lock object captured from the enclosing scope, or better, I reach for a concurrency utility like AtomicInteger or ConcurrentHashMap when possible."