国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

ホームページ Java &#&チュートリアル Belay the Metamorphosis: Kafka プロジェクトの分析

Belay the Metamorphosis: Kafka プロジェクトの分析

Oct 16, 2024 pm 08:09 PM

您有沒有想過跨國公司的專案原始碼中可能潛藏著哪些錯誤?不要錯過在開源 Apache Kafka 專案中發(fā)現(xiàn) PVS-Studio 靜態(tài)分析器偵測到的有趣錯誤的機會。

Belay the Metamorphosis: analyzing Kafka project

介紹

Apache Kafka 是一個著名的開源項目,主要用 Java 寫。 LinkedIn 於 2011 年將其開發(fā)為訊息代理,即各種系統(tǒng)元件的資料管道。如今,它已成為同類產(chǎn)品中最受歡迎的解決方案之一。

準(zhǔn)備好看看引擎蓋下的內(nèi)容了嗎?

附註
只是想簡單說明一下標(biāo)題。它參考了弗朗茨·卡夫卡的《變形記》,其中主角變成了可怕的害蟲。我們的靜態(tài)分析器致力於防止您的專案變身為可怕的害蟲轉(zhuǎn)變?yōu)橐粋€巨大的錯誤,所以對「變形記」說不。

喔不,蟲子

所有的幽默都源自於痛苦

這不是我的話;這句話出自理查德·普賴爾之口。但這有什麼關(guān)係呢?我想告訴你的第一件事是一個愚蠢的錯誤。然而,在多次嘗試?yán)斫獬淌綗o法正常運作的原因後,遇到以下範(fàn)例的情況令人沮喪:

@Override
public KeyValueIterator<Windowed<K>, V> backwardFetch(
  K keyFrom,
  K keyTo,
  Instant timeFrom,
  Instant timeTo) {
  ....
  if (keyFrom == null && keyFrom == null) {   // <=
    kvSubMap = kvMap;
  } else if (keyFrom == null) {
    kvSubMap = kvMap.headMap(keyTo, true);
  } else if (keyTo == null) {
    kvSubMap = kvMap.tailMap(keyFrom, true);
  } else {
    // keyFrom != null and KeyTo != null 
    kvSubMap = kvMap.subMap(keyFrom, true, keyTo, true);
  } 
  ....
}

如您所見,這是任何開發(fā)人員都無法避免的事情——一個微不足道的拼字錯誤。在第一個條件下,開發(fā)人員希望使用下列邏輯表達(dá)式:

keyFrom == null && keyTo == null

分析器發(fā)出兩個警告:

V6001 在「&&」運算子的左邊和右邊有相同的子運算式「keyFrom == null」。 ReadOnlyWindowStoreStub.java 327、ReadOnlyWindowStoreStub.java 327

V6007 表達(dá)式「keyFrom == null」總是 false。 ReadOnlyWindowStoreStub.java 329

我們可以明白為什麼。對於每個開發(fā)人員來說,這種可笑的打字錯誤都是永恆的。雖然我們可以花很多時間尋找它們,但要回憶起它們潛伏的地方可不是小菜一碟。

在同一個類別中,另一個方法中存在完全相同的錯誤。我認(rèn)為稱其為複製麵食是公平的。

@Override
public KeyValueIterator<Windowed<K>, V> fetch(
  K keyFrom,
  K keyTo,
  Instant timeFrom,
  Instant timeTo) {
  ....
  NavigableMap<K, V> kvMap = data.get(now);
  if (kvMap != null) {
    NavigableMap<K, V> kvSubMap;
    if (keyFrom == null && keyFrom == null) {      // <=
      kvSubMap = kvMap;
    } else if (keyFrom == null) {
      kvSubMap = kvMap.headMap(keyTo, true);
    } else if (keyTo == null) {
      kvSubMap = kvMap.tailMap(keyFrom, true);
    } else {
      // keyFrom != null and KeyTo != null
      kvSubMap = kvMap.subMap(keyFrom, true, keyTo, true);
    }
  }
  ....
}

以下是相同的警告:

V6007 表達(dá)式「keyFrom == null」總是 false。 ReadOnlyWindowStoreStub.java 273

V6001 在「&&」運算子的左邊和右邊有相同的子運算式「keyFrom == null」。 ReadOnlyWindowStoreStub.java 271, ReadOnlyWindowStoreStub.java 271

不用擔(dān)心——我們不必一次查看數(shù)百行程式碼。 PVS-Studio 非常擅長處理這類簡單的事情。解決一些更具挑戰(zhàn)性的事情怎麼樣?

可變同步

Java 中 synchronized 關(guān)鍵字的用途是什麼?在這裡,我將只關(guān)注同步方法,而不是區(qū)塊。根據(jù) Oracle 文檔,synchronized 關(guān)鍵字將方法聲明為同步,以確保與實例的線程安全互動。如果一個執(zhí)行緒呼叫該實例的同步方法,則嘗試呼叫相同實例的同步方法的其他執(zhí)行緒將被阻塞(即它們的執(zhí)行將被掛起)。它們將被阻塞,直到第一個執(zhí)行緒呼叫的方法處理其執(zhí)行。當(dāng)實例對多個執(zhí)行緒可見時,需要執(zhí)行此操作。此類實例的讀取/寫入操作只能透過同步方法執(zhí)行。

開發(fā)人員違反了 Sensor 類別中的規(guī)則,如下面的簡化程式碼片段所示。實例欄位的讀取/寫入操作可以透過同步和非同步兩種方式執(zhí)行。它可能會導(dǎo)致競爭條件並使輸出變得不可預(yù)測。

private final Map<MetricName, KafkaMetric> metrics;

public void checkQuotas(long timeMs) {                  // <=
  for (KafkaMetric metric : this.metrics.values()) {
    MetricConfig config = metric.config();
    if (config != null) {
      ....
    }
  }
  ....
}  

public synchronized boolean add(CompoundStat stat,      // <=
                                MetricConfig config) {       
  ....
  if (!metrics.containsKey(metric.metricName())) {         
    metrics.put(metric.metricName(), metric);            
  }  
  ....
}  

public synchronized boolean add(MetricName metricName,  // <=
                                MeasurableStat stat, 
                                MetricConfig config) {  
  if (hasExpired()) {
    return false;
  } else if (metrics.containsKey(metricName)) {
    return true;
  } else {
    ....
    metrics.put(metric.metricName(), metric);
    return true;
  }
}

分析器警告如下:

V6102 “metrics”欄位同步不一致。考慮在所有用途上同步該欄位。感測器.java 49,感測器.java 254

如果不同的執(zhí)行緒可以同時變更實例狀態(tài),則允許此操作的方法應(yīng)該同步。如果程式?jīng)]有預(yù)料到多個執(zhí)行緒可以與實例交互,則使其方法同步是沒有意義的。最壞的情況下,甚至?xí)p害程式效能。

程式中有很多這樣的錯誤。這是分析器發(fā)出警告的類似程式碼片段:

private final PrefixKeyFormatter prefixKeyFormatter; 

@Override
public synchronized void destroy() {                // <=
  ....
  Bytes keyPrefix = prefixKeyFormatter.getPrefix();
  ....
}

@Override
public void addToBatch(....) {                      // <=
  physicalStore.addToBatch(
    new KeyValue<>(
    prefixKeyFormatter.addPrefix(record.key),
    record.value
    ), batch
  );
} 

@Override
public synchronized void deleteRange(....) {        // <=
  physicalStore.deleteRange(
    prefixKeyFormatter.addPrefix(keyFrom),
    prefixKeyFormatter.addPrefix(keyTo)
  );
}

@Override
public synchronized void put(....) {                // <=
  physicalStore.put(
    prefixKeyFormatter.addPrefix(key),
    value
  );
}

分析器警告:

V6102 “prefixKeyFormatter”欄位同步不一致??紤]在所有用途上同步該欄位。 LogicalKeyValueSegment.java 60、LogicalKeyValueSegment.java 247

Iterator, iterator, and iterator again...

In the example, there are two rather unpleasant errors within one line at once. I'll explain their nature within the part of the article. Here's a code snippet:

private final Map<String, Uuid> topicIds = new HashMap(); 

private Map<String, KafkaFutureVoid> handleDeleteTopicsUsingNames(....) { 
  ....
  Collection<String> topicNames = new ArrayList<>(topicNameCollection);

  for (final String topicName : topicNames) {
    KafkaFutureImpl<Void> future = new KafkaFutureImpl<>();

    if (allTopics.remove(topicName) == null) {
      ....
    } else {
      topicNames.remove(topicIds.remove(topicName));      // <=
      future.complete(null);
    }
    ....
  }
}

That's what the analyzer shows us:

V6066 The type of object passed as argument is incompatible with the type of collection: String, Uuid. MockAdminClient.java 569

V6053 The 'topicNames' collection of 'ArrayList' type is modified while iteration is in progress. ConcurrentModificationException may occur. MockAdminClient.java 569

Now that's a big dilemma! What's going on here, and how should we address it?!

First, let's talk about collections and generics. Using the generic types of collections helps us avoid ClassCastExceptions and cumbersome constructs where we convert types.

If we specify a certain data type when initializing a collection and add an incompatible type, the compiler won't compile the code.

Here's an example:

public class Test {
  public static void main(String[] args) {
    Set<String> set = new HashSet<>();
    set.add("str");
    set.add(UUID.randomUUID()); // java.util.UUID cannot be converted to
                                // java.lang.String
  }
}

However, if we delete an incompatible type from our Set, no exception will be thrown. The method returns false.

Here's an example:

public class Test {
  public static void main(String[] args) {
    Set<String> set = new HashSet<>();
    set.add("abc");
    set.add("def");
    System.out.println(set.remove(new Integer(13))); // false
  }
}

It's a waste of time. Most likely, if we encounter something like this in the code, this is an error. I suggest you go back to the code at the beginning of this subchapter and try to spot a similar case.

Second, let's talk about the Iterator. We can talk about iterating through collections for a long time. I don't want to bore you or digress from the main topic, so I'll just cover the key points to ensure we understand why we get the warning.

So, how do we iterate through the collection here? Here is what the for loop in the code fragment looks like:

for (Type collectionElem : collection) {
  ....
}

The for loop entry is just syntactic sugar. The construction is equivalent to this one:

for (Iterator<Type> iter = collection.iterator(); iter.hasNext();) {
  Type collectionElem = iter.next();
  ....
}

We're basically working with the collection iterator. All right, that's sorted! Now, let's discuss ConcurrentModificationException.

ConcurrentModificationException is an exception that covers a range of situations both in single-threaded and multi-threaded programs. Here, we're focusing on single-threading. We can find an explanation quite easily. Let's take a peek at the Oracle docs: a method can throw the exception when it detects parallel modification of an object that doesn't support it. In our case, while the iterator is running, we delete objects from the collection. This may cause the iterator to throw a ConcurrentModificationException.

How does the iterator know when to throw the exception? If we look at the ArrayList collection, we see that its parent, AbstactList, has the modCount field that stores the number of modifications to the collection:

protected transient int modCount = 0;

Here are some usages of the modCount counter in the ArrayList class:

public boolean add(E e) {
  modCount++;
  add(e, elementData, size);
  return true;
}

private void fastRemove(Object[] es, int i) {
  modCount++;
  final int newSize;
  if ((newSize = size - 1) > i)
    System.arraycopy(es, i + 1, es, i, newSize - i);
  es[size = newSize] = null;
}

So, the counter is incremented each time when the collection is modified.

Btw, the fastRemove method is used in the remove method, which we use inside the loop.

Here's the small code fragment of the ArrayList iterator inner workings:

private class Itr implements Iterator<E> {
  ....
  int expectedModCount = modCount;            

  final void checkForComodification() {
  if (modCount != expectedModCount)               // <=
    throw new ConcurrentModificationException();
  }

  public E next() {
    checkForComodification();              
    ....
  }

  public void remove() {
    ....
    checkForComodification();             

    try {
      ArrayList.this.remove(lastRet);   
      ....
      expectedModCount = modCount;
    } catch (IndexOutOfBoundsException ex) {
      throw new ConcurrentModificationException();
    }
  }
  ....
  public void add(E e) {
    checkForComodification();            
    try {
      ....
      ArrayList.this.add(i, e);        
      ....
      expectedModCount = modCount;     
    } catch (IndexOutOfBoundsException ex) {
      throw new ConcurrentModificationException();
    }
  }
}

Let me explain that last fragment. If the collection modifications don't match the expected number of modifications (which is the sum of the initial modifications before the iterator was created and the number of the iterator operations), a ConcurrentModificationException is thrown. That's only possible when we modify the collection using its methods while iterating over it (i.e. in parallel with the iterator). That's what the second warning is about.

So, I've explained you the analyzer messages. Now let's put it all together:

We attempt to delete an element from the collection when the Iterator is still running:

topicNames.remove(topicIds.remove(topicName)); 
// topicsNames – Collection<String>
// topicsIds – Map<String, UUID>

However, since the incompatible element is passed to ArrayList for deletion (the remove method returns a UUID object from topicIds), the modification count won't increase, but the object won't be deleted. Simply put, that code section is rudimentary.

I'd venture to guess that the developer's intent is clear. If that's the case, one way to fix these two warnings could be as follows:

Collection<String> topicNames = new ArrayList<>(topicNameCollection);

List<String> removableItems = new ArrayList<>();

for (final String topicName : topicNames) {
  KafkaFutureImpl<Void> future = new KafkaFutureImpl<>();

  if (allTopics.remove(topicName) == null) {
    ....
  } else {
    topicIds.remove(topicName);
    removableItems.add(topicName);
    future.complete(null);
  }
  ....
}
topicNames.removeAll(removableItems);

Void, sweet void

Where would we go without our all-time favorite null and its potential problems, right? Let me show you the code fragment for which the analyzer issued the following warning:

V6008 Potential null dereference of 'oldMember' in function 'removeStaticMember'. ConsumerGroup.java 311, ConsumerGroup.java 323

@Override
public void removeMember(String memberId) {
  ConsumerGroupMember oldMember = members.remove(memberId);
  ....
  removeStaticMember(oldMember);
  ....
}

private void removeStaticMember(ConsumerGroupMember oldMember) {
  if (oldMember.instanceId() != null) {
    staticMembers.remove(oldMember.instanceId());
  }
}

If members doesn't contain an object with the memberId key, oldMember will be null. It can lead to a NullPointerException in the removeStaticMember method.

Boom! The parameter is checked for null:

if (oldMember != null && oldMember.instanceId() != null) {

The next error will be the last one in the article—I'd like to wrap things up on a positive note. The code below—as well as the one at the beginning of this article—has a common and silly typo. However, it can certainly lead to unpleasant consequences.

Let's take a look at this code fragment:

protected SchemaAndValue roundTrip(...., SchemaAndValue input) {
  String serialized = Values.convertToString(input.schema(),
                                             input.value());

  if (input != null && input.value() != null) {   
    ....
  }
  ....
}

Yeah, that's right. The method actually accesses the input object first, and then checks whether it's referencing null.

V6060 The 'input' reference was utilized before it was verified against null. ValuesTest.java 1212, ValuesTest.java 1213

Again, I'll note that such typos are ok. However, they can lead to some pretty nasty results. It's tough and inefficient to search for these things in the code manually.

Conclusion

In sum, I'd like to circle back to the previous point. Manually searching through the code for all these errors is a very time-consuming and tedious task. It's not unusual for issues like the ones I've shown to lurk in code for a long time. The last bug dates back to 2018. That's why it's a good idea to use static analysis tools. If you'd like to know more about PVS-Studio, the tool we have used to detect all those errors, you can find out more here.

That's all. Let's wrap things up here. "Oh, and in case I don't see ya, good afternoon, good evening, and good night."

Belay the Metamorphosis: analyzing Kafka project

I almost forgot! Catch a link to learn more about a free license for open-source projects.

以上がBelay the Metamorphosis: Kafka プロジェクトの分析の詳細(xì)內(nèi)容です。詳細(xì)については、PHP 中國語 Web サイトの他の関連記事を參照してください。

このウェブサイトの聲明
この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當(dāng)する法的責(zé)任を負(fù)いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。

ホットAIツール

Undress AI Tool

Undress AI Tool

脫衣畫像を無料で

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード寫真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

寫真から衣服を削除するオンライン AI ツール。

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中國語版

SublimeText3 中國語版

中國語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統(tǒng)合開発環(huán)境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

ハッシュマップとハッシュテーブルの違いは? ハッシュマップとハッシュテーブルの違いは? Jun 24, 2025 pm 09:41 PM

ハッシュマップとハッシュテーブルの違いは、主にスレッドの安全性、ヌル価値のサポート、パフォーマンスに反映されます。 1.スレッドの安全性の観點から、ハッシュテーブルはスレッドセーフであり、その方法はほとんど同期メソッドであり、ハッシュマップはスレッドセーフではない同期処理を?qū)g行しません。 2。ヌル値のサポートに関しては、ハッシュマップは1つのnullキーと複數(shù)のヌル値を許可しますが、ハッシュテーブルはnullキーや値を許可しません。 3.パフォーマンスの観點から、ハッシュマップは同期メカニズムがないため、より効率的です。ハッシュテーブルは、各操作のロックパフォーマンスが低いです。代わりにconcurrenthashmapを使用することをお勧めします。

なぜラッパークラスが必要なのですか? なぜラッパークラスが必要なのですか? Jun 28, 2025 am 01:01 AM

Javaは、基本的なデータ型がオブジェクト指向の操作に直接參加できないため、ラッパークラスを使用し、実際のニーズでオブジェクトフォームが必要になることが多いためです。 1.コレクションクラスは、リストが自動ボクシングを使用して數(shù)値を保存するなど、オブジェクトのみを保存できます。 2。ジェネリックは基本的なタイプをサポートしておらず、パッケージングクラスはタイプパラメーターとして使用する必要があります。 3.パッケージングクラスは、null値を表して、データまたは欠落データを區(qū)別できます。 4.パッケージングクラスは、データの解析と処理を容易にするための文字列変換などの実用的な方法を提供するため、これらの特性が必要なシナリオでは、パッケージングクラスは不可欠です。

インターフェイスの靜的メソッドとは何ですか? インターフェイスの靜的メソッドとは何ですか? Jun 24, 2025 pm 10:57 PM

StaticMethodsinInterfaceswereIntroducatedinjava8toalowutilityは、interfaceitself.beforejava8、そのような導(dǎo)入のために導(dǎo)入されたコード、rediveTodisorgedCode.now、statecmethodssprovidreebenefits:1)彼らの可能性のある測定di

JITコンパイラはどのようにコードを最適化しますか? JITコンパイラはどのようにコードを最適化しますか? Jun 24, 2025 pm 10:45 PM

JITコンパイラは、メソッドインライン、ホットスポット検出とコンピレーション、タイプの投機と偏見、冗長操作の排除の4つの方法を通じてコードを最適化します。 1。メソッドインラインで呼び出しのオーバーヘッドを減らし、頻繁に小さな方法と呼ばれる挿入をコールに直接直接挿入します。 2。ホットスポットの検出と高周波コードの実行とそれを中央に最適化して、リソースを節(jié)約します。 3。タイプ投機は、敬v的な呼び出しを達(dá)成するためにランタイムタイプ情報を収集し、効率を向上させます。 4.冗長操作は、運用データの削除に基づいて役に立たない計算と検査を排除し、パフォーマンスを向上させます。

インスタンスイニシャルイザーブロックとは何ですか? インスタンスイニシャルイザーブロックとは何ですか? Jun 25, 2025 pm 12:21 PM

インスタンス初期化ブロックは、Javaで使用され、コンストラクターの前に実行されるオブジェクトを作成するときに初期化ロジックを?qū)g行します。複數(shù)のコンストラクターが初期化コード、複雑なフィールド初期化、または匿名のクラス初期化シナリオを共有するシナリオに適しています。靜的初期化ブロックとは異なり、インスタンス化されるたびに実行されますが、靜的初期化ブロックはクラスがロードされたときに1回のみ実行されます。

変數(shù)の「ファイナル」キーワードは何ですか? 変數(shù)の「ファイナル」キーワードは何ですか? Jun 24, 2025 pm 07:29 PM

Injava、thefinalkeywordpreventsavariaibleのValue frombeingededafterassignment、ButiTsbehiviordiffersforprimitivesandobjectReferences

工場のパターンとは何ですか? 工場のパターンとは何ですか? Jun 24, 2025 pm 11:29 PM

ファクトリーモードは、オブジェクトの作成ロジックをカプセル化するために使用され、コードをより柔軟でメンテナンスしやすく、ゆるく結(jié)合します。コアの答えは、オブジェクトの作成ロジックを一元的に管理し、実裝の詳細(xì)を隠し、複數(shù)の関連オブジェクトの作成をサポートすることです。特定の説明は次のとおりです。工場モードは、NewClass()の使用を直接回避し、処理のための特別な工場クラスまたは方法にオブジェクトの作成を手渡します。複數(shù)のタイプの関連オブジェクトが作成され、作成ロジックが変更され、実裝の詳細(xì)を非表示にする必要があるシナリオに適しています。たとえば、支払いプロセッサでは、Stripe、PayPal、その他のインスタンスが工場を通じて作成されます。その実裝には、入力パラメーターに基づいて工場クラスによって返されるオブジェクトが含まれ、すべてのオブジェクトは共通のインターフェイスを?qū)g現(xiàn)します。一般的なバリアントには、単純な工場、工場法、抽象的な工場が含まれます。これらは異なる複雑さに適しています。

タイプキャストとは何ですか? タイプキャストとは何ですか? Jun 24, 2025 pm 11:09 PM

変換には、暗黙的で明示的な変換には2つのタイプがあります。 1.暗黙的な変換は、INTを2倍に変換するなど、自動的に発生します。 2。明示的な変換には、(int)mydoubleの使用など、手動操作が必要です。タイプ変換が必要な場合には、ユーザー入力の処理、數(shù)學(xué)操作、または関數(shù)間のさまざまなタイプの値の渡されます。注意する必要がある問題は次のとおりです。浮動小數(shù)點數(shù)を整數(shù)に変換すると、分?jǐn)?shù)部分が切り捨てられ、大きなタイプを小さなタイプに変えるとデータの損失につながる可能性があり、一部の言語では特定のタイプの直接変換ができません。言語変換ルールを適切に理解することは、エラーを回避するのに役立ちます。

See all articles