Skip to content
Advertisement

how to add synchronization in following lambda exp?

   {
List<Integer> list = new ArrayList<>(10000);
        
IntStream.range(1, 10000).forEach(list::add);

Thread reader = new Thread(() ->  {
            list.forEach(i -> System.out.println("r " + i));
        }, "t1");
}

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

Advertisement

Answer

It is possible to use synchronized blocks inside a Java Lambda Expression and inside anonymous classes.

Note: You have forgotten to add code snippet as no code snippet is visible in your code , So I ma adding my own code snippet to make clear my point.

    import java.util.function.Consumer;

public class SynchronizedExample {

  public static void main(String[] args) {

    Consumer<String> func = (String param) -> {

      synchronized(SynchronizedExample.class) {

        System.out.println(
            Thread.currentThread().getName() +
                    " step 1: " + param);

        try {
          Thread.sleep( (long) (Math.random() * 1000));
        } catch (InterruptedException e) {
          e.printStackTrace();
        }

        System.out.println(
            Thread.currentThread().getName() +
                    " step 2: " + param);
      }

    };


    Thread thread1 = new Thread(() -> {
        func.accept("Parameter");
    }, "Thread 1");

    Thread thread2 = new Thread(() -> {
        func.accept("Parameter");
    }, "Thread 2");

    thread1.start();
    thread2.start();
  }
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement