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

Spiking bond yields driving sharp losses in tech stocks

A spike in interest rates since the start of the year has accelerated a rotation out of high-growth technology stocks and into value stocks poised to benefit from a reopening of the economy. The Nasdaq has fallen more than 10% over the past month as the Dow has soared to record highs, with a spike in the 10-year US Treasury yield acting as the main catalyst. It recently surged to a cycle high of more than 1.60% after starting the year below 1%. But according to Jim Paulsen, the Leuthold Group's chief investment strategist, rising interest rates do not represent a long-term threat to the stock market. Paulsen expects the 10-year yield to cross 2% by the end of the year. A spike in interest rates and its impact on the stock market depends on the economic backdrop, according to Paulsen. Rising interest rates amid a strengthening economy "may prove no challenge at all for stocks," Paulsen said.

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 tw


Telegram Java
FROM USA