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: |

Export WhatsApp stickers to Telegram on iPhone

You can’t. What you can do, though, is use WhatsApp’s and Telegram’s web platforms to transfer stickers. It’s easy, but might take a while.Open WhatsApp in your browser, find a sticker you like in a chat, and right-click on it to save it as an image. The file won’t be a picture, though—it’s a webpage and will have a .webp extension. Don’t be scared, this is the way. Repeat this step to save as many stickers as you want.Then, open Telegram in your browser and go into your Saved messages chat. Just as you’d share a file with a friend, click the Share file button on the bottom left of the chat window (it looks like a dog-eared paper), and select the .webp files you downloaded. Click Open and you’ll see your stickers in your Saved messages chat. This is now your sticker depository. To use them, forward them as you would a message from one chat to the other: by clicking or long-pressing on the sticker, and then choosing Forward.

Telegram has exploded as a hub for cybercriminals looking to buy, sell and share stolen data and hacking tools, new research shows, as the messaging app emerges as an alternative to the dark web.An investigation by cyber intelligence group Cyberint, together with the Financial Times, found a ballooning network of hackers sharing data leaks on the popular messaging platform, sometimes in channels with tens of thousands of subscribers, lured by its ease of use and light-touch moderation.Java from br


Telegram Java
FROM USA