Telegram Group & Telegram Channel
💥 Задача: Почему эта структура «ломается» в многопоточной среде?


import java.util.*;

public class BrokenImmutable {
private final Map<String, List<String>> data;

public BrokenImmutable(Map<String, List<String>> input) {
this.data = Collections.unmodifiableMap(input);
}

public Map<String, List<String>> getData() {
return data;
}

public static void main(String[] args) {
Map<String, List<String>> base = new HashMap<>();
base.put("key", new ArrayList<>(List.of("a")));

BrokenImmutable bi = new BrokenImmutable(base);
Map<String, List<String>> d = bi.getData();

d.get("key").add("🚨");

System.out.println(bi.getData());
}
}


🔍 Разбор:
С первого взгляда кажется, что BrokenImmutable — иммутабельный класс. Мы оборачиваем Map через Collections.unmodifiableMap, и поле data — final.

Но проблема в глубине структуры.

unmodifiableMap запрещает перезапись ключей, но не делает элементы внутри truly immutable. В данном случае, значение по ключу "key" — это ArrayList, которую легко модифицировать.

💣 В main() мы получили доступ к внутреннему списку и… тихо сломали инвариант класса, добавив "🚨".

Решение:
Чтобы сделать структуру действительно иммутабельной, нужно:

Копировать и оборачивать значения внутри Map.

Сделать глубокую защиту:


public BrokenImmutable(Map<String, List<String>> input) {
Map<String, List<String>> copy = new HashMap<>();
for (Map.Entry<String, List<String>> e : input.entrySet()) {
copy.put(e.getKey(), List.copyOf(e.getValue())); // immutable list
}
this.data = Map.copyOf(copy); // immutable map
}



Теперь никто не сможет мутировать data, даже если получит на него ссылку.

🧠 Вопрос на подумать:
А что если вместо ArrayList внутри Map был бы CopyOnWriteArrayList или ImmutableList от Guava? Почему CopyOnWriteArrayList — тоже плохой выбор для truly immutable структур?

@javatg



tg-me.com/javatg/1869
Create:
Last Update:

💥 Задача: Почему эта структура «ломается» в многопоточной среде?


import java.util.*;

public class BrokenImmutable {
private final Map<String, List<String>> data;

public BrokenImmutable(Map<String, List<String>> input) {
this.data = Collections.unmodifiableMap(input);
}

public Map<String, List<String>> getData() {
return data;
}

public static void main(String[] args) {
Map<String, List<String>> base = new HashMap<>();
base.put("key", new ArrayList<>(List.of("a")));

BrokenImmutable bi = new BrokenImmutable(base);
Map<String, List<String>> d = bi.getData();

d.get("key").add("🚨");

System.out.println(bi.getData());
}
}


🔍 Разбор:
С первого взгляда кажется, что BrokenImmutable — иммутабельный класс. Мы оборачиваем Map через Collections.unmodifiableMap, и поле data — final.

Но проблема в глубине структуры.

unmodifiableMap запрещает перезапись ключей, но не делает элементы внутри truly immutable. В данном случае, значение по ключу "key" — это ArrayList, которую легко модифицировать.

💣 В main() мы получили доступ к внутреннему списку и… тихо сломали инвариант класса, добавив "🚨".

Решение:
Чтобы сделать структуру действительно иммутабельной, нужно:

Копировать и оборачивать значения внутри Map.

Сделать глубокую защиту:


public BrokenImmutable(Map<String, List<String>> input) {
Map<String, List<String>> copy = new HashMap<>();
for (Map.Entry<String, List<String>> e : input.entrySet()) {
copy.put(e.getKey(), List.copyOf(e.getValue())); // immutable list
}
this.data = Map.copyOf(copy); // immutable map
}



Теперь никто не сможет мутировать data, даже если получит на него ссылку.

🧠 Вопрос на подумать:
А что если вместо ArrayList внутри Map был бы CopyOnWriteArrayList или ImmutableList от Guava? Почему CopyOnWriteArrayList — тоже плохой выбор для truly immutable структур?

@javatg

BY Java


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/javatg/1869

View MORE
Open in Telegram


Java Telegram | DID YOU KNOW?

Date: |

Find Channels On Telegram?

Telegram is an aspiring new messaging app that’s taking the world by storm. The app is free, fast, and claims to be one of the safest messengers around. It allows people to connect easily, without any boundaries.You can use channels on Telegram, which are similar to Facebook pages. If you’re wondering how to find channels on Telegram, you’re in the right place. Keep reading and you’ll find out how. Also, you’ll learn more about channels, creating channels yourself, and the difference between private and public Telegram channels.

Telegram today rolling out an update which brings with it several new features.The update also adds interactive emoji. When you send one of the select animated emoji in chat, you can now tap on it to initiate a full screen animation. The update also adds interactive emoji. When you send one of the select animated emoji in chat, you can now tap on it to initiate a full screen animation. This is then visible to you or anyone else who's also present in chat at the moment. The animations are also accompanied by vibrations. This is then visible to you or anyone else who's also present in chat at the moment. The animations are also accompanied by vibrations.

Java from pl


Telegram Java
FROM USA